
Sponsored
Sponsored
This approach uses recursion to explore all possible valid splits and checks if either of the permutations exist. To avoid re-computation, use a dictionary to memoize already computed results for specific substrings.
Time Complexity: O(N^4), where N is the length of the strings.
Space Complexity: O(N^3), used by the memoization array.
1#include <string>
2#include <unordered_map>
3using namespace std;
4
5class Solution {
6 unordered_map<string, bool> memo;
7public:
8 bool isScramble(string s1, string s2) {
9 if (s1 == s2) return true;
10 int n = s1.size();
11 string key = s1 + " " + s2;
12 if (memo.count(key)) return memo[key];
13 if (!hasSameChars(s1, s2)) return false;
14 for (int i = 1; i < n; ++i) {
15 if ((isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i))) ||
16 (isScramble(s1.substr(0, i), s2.substr(n - i)) && isScramble(s1.substr(i), s2.substr(0, n - i)))) {
17 return memo[key] = true;
18 }
19 }
20 return memo[key] = false;
21 }
22private:
23 bool hasSameChars(const string &s1, const string &s2) {
24 int charCount[26] = {0};
25 for (char c : s1) charCount[c - 'a']++;
26 for (char c : s2) charCount[c - 'a']--;
27 for (int count : charCount) if (count != 0) return false;
28 return true;
29 }
30};This C++ solution uses recursion with memoization and string manipulation. The memoization map reduces redundant computations by storing results for string combinations. The hasSameChars function checks for character equality in the substrings, pruning unnecessary calculations.
This approach is based on dynamic programming. We set up a 3D table where table[i][j][k] holds true if s1's substring starting at index i with length k is a scrambled string of s2's substring starting at index j.
Time Complexity: O(N^4), where N is the length of the strings.
Space Complexity: O(N^3), due to the 3D DP table.
1#
In this C solution, we use a 3D boolean DP array dp with indices [i][j][k] indicating whether a substring starting at index i in s1 and a substring starting at index j in s2 of length k can be scrambles of each other. We fill this array iteratively, considering the divisions of the k-length substring into parts.