Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
Below is one possible representation of s1 = "great"
:
great / gr eat / / g r e at / a t
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node "gr"
and swap its two children, it produces a scrambled string "rgeat"
.
rgeat / rg eat / / r g e at / a t
We say that "rgeat"
is a scrambled string of "great"
.
Similarly, if we continue to swap the children of nodes "eat"
and "at"
, it produces a scrambled string "rgtae"
.
rgtae / rg tae / / r g ta e / t a
We say that "rgtae"
is a scrambled string of "great"
.
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
1 class Solution { 2 public: 3 bool check(string s1, string s2) { 4 if(s1.length() != s2.length()) return false; 5 6 string cp1 = s1, cp2 = s2; 7 sort(cp1.begin(), cp1.end()); 8 sort(cp2.begin(), cp2.end()); 9 for(int i=0; i<cp1.length(); ++i) { 10 if(cp1[i] != cp2[i]) return false; 11 } 12 return true; 13 } 14 bool dfs(string s1, string s2) { 15 int m = s1.length(), n = s2.length(); 16 if(!check(s1, s2)) return false; 17 if(m == 1) { 18 if(s1 == s2) return true; 19 return false; 20 } 21 22 string l, r, p, q; 23 for(int le = 1; le < m; ++le) { 24 l = s1.substr(0, le); 25 r = s1.substr(le, m - le); 26 p = s2.substr(0, le); 27 q = s2.substr(le, m - le); 28 if(dfs(l, p) && dfs(r, q)) return true; 29 else { 30 p = s2.substr(m - le, le); 31 q = s2.substr(0, m - le); 32 if(dfs(l, p) && dfs(r, q)) return true; 33 } 34 } 35 36 return false; 37 } 38 39 bool isScramble(string s1, string s2) { 40 int m = s1.length(), n = s2.length(); 41 42 if(m != n) return false; 43 44 return dfs(s1, s2); 45 } 46 };