Scramble String
Given A string S1, we may represent it as a binary tree by partitioning it to the Non-empty substrings Recursivel Y.
Below is one possible representation of S1 = "great"
:
Great / gr eat/\ / g r E at / a t
To scramble the string, we are choose any non-leaf node and swap it to the children.
For example, if we choose the node "gr"
and swaps its-children, it produces a scrambled string "rgeat"
.
Rgeat / RG eat/\ / r G e at / a t
We say is "rgeat"
a scrambled string of "great"
.
Similarly, if we continue to swap the children of nodes "eat"
"at"
and, it produces a scrambled string "rgtae"
.
Rgtae / RG tae/\ / r G ta e / t a
We say is "rgtae"
a scrambled string of "great"
.
Given strings S1 and S2 of the same length, determine if S2 is a scrambled string of S1.
Handed back to do, that is S1 divided into S11 and s12,s2 divided into S21 and S22.
Judge Isscramble (S11,S21) &&isscramble (S12,S22) or isscramble (S12,S21) &&isscramble (S11,S22)
Base case is the same as String
In addition, pruning is required before entering recursion to determine whether two strings contain the same letter, O (n) complexity. Reference http://blog.csdn.net/doc_sgl/article/details/12401335
classSolution { Public: BOOLIsscramble (stringS1,stringS2) { //Base Case if(S1 = =S2)return true; //to here, S1! = S2//Check permutationvector<int> Dict ( -,0);//a~z for(inti =0; I < s1.size (); i + +) Dict[s1[i]-'a'] ++; for(inti =0; I < s2.size (); i + +) Dict[s2[i]-'a'] --; for(inti =0; I < dict.size (); i + +) if(Dict[i]! =0) return false; //to here, S1 and S2 must has same size intSize =s1.size (); //recursion for(inti =1; i < size; i + +) { if((Isscramble (S1.substr (0, i), S2.substr (0, i)) &&isscramble (S1.substr (i), s2.substr (i)))|| (Isscramble (S1.substr (0, i), S2.substr (size-i)) &&isscramble (S1.substr (i), S2.substr (0, size-i) ))return true; } return false; }};
"Leetcode" Scramble String