|
| 1 | +// Time Complexity: O(n^4), due to enumeration of n, i, j, k in (f[n][i][j] and k) |
| 2 | +// Space Complexity: O(n^3), due to hash of f[n][i][j] |
| 3 | + |
| 4 | +class Solution { |
| 5 | + public: |
| 6 | + bool isScramble(string s1, string s2) { |
| 7 | + if(s1.size() != s2.size()) |
| 8 | + return false; |
| 9 | + return isScramble(s1.size(), s1.begin(), s2.begin()); |
| 10 | + } |
| 11 | + private: |
| 12 | + typedef string::const_iterator Iterator; |
| 13 | + map<tuple<int, Iterator, Iterator>, bool> hash; |
| 14 | + |
| 15 | + bool isScramble(int n, Iterator s1, Iterator s2) { |
| 16 | + // hash |
| 17 | + if( hash.find(make_tuple(n, s1, s2)) != hash.end()) return hash[make_tuple(n, s1, s2)]; |
| 18 | + |
| 19 | + if(n == 1) return *s1 == *s2; |
| 20 | + |
| 21 | + // pruning |
| 22 | + int value1 = 0, value2=0; |
| 23 | + for (auto it1 = s1, it2 = s2; it1 != s1 + n; ++it1, ++it2) { |
| 24 | + value1 += (*it1-'a'); |
| 25 | + value2 += (*it2-'a'); |
| 26 | + } |
| 27 | + if (value1 != value2) |
| 28 | + return hash[make_tuple(n, s1, s2)] = false; |
| 29 | + |
| 30 | + // recursive |
| 31 | + for(int k = 1; k < n; ++k) { |
| 32 | + if((isScramble(k, s1, s2) && isScramble(n - k, s1 + k, s2 + k)) |
| 33 | + || (isScramble(k, s1, s2 + n - k) && isScramble(n - k, s1 + k, s2)) ) { |
| 34 | + return hash[make_tuple(n, s1, s2)] = true; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return hash[make_tuple(n, s1, s2)] = false; |
| 39 | + } |
| 40 | + |
| 41 | +}; |
0 commit comments