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 bool isScramble(string s1, string s2) { 2 string comp1=s1,comp2=s2; 3 sort(comp1.begin(),comp1.end()); 4 sort(comp2.begin(),comp2.end()); 5 if(comp1!=comp2) 6 return false; 7 if(comp1.length()==1) 8 return true; 9 int len=s1.length(); 10 int i; 11 for(i=1;i<len;i++) 12 { 13 string s1_left=s1.substr(0,i); 14 string s1_right=s1.substr(i); 15 string s2_left=s2.substr(0,i); 16 string s2_right=s2.substr(i); 17 if(isScramble(s1_left,s2_left)&&isScramble(s1_right,s2_right)) 18 return true; 19 s2_left=s2.substr(len-i); 20 s2_right=s2.substr(0,len-i); 21 if(isScramble(s1_left,s2_left)&&isScramble(s1_right,s2_right)) 22 return true; 23 } 24 return false; 25 26 27 }