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.
Ideas:
1. If there is only one s1.length = = S2.length = = 1, then just judge S1 = = S2;
2. If s1.length = = S2.length = = 2; You need to judge (s1[0] = s2[0] && s1[1]==s2[1]) | | (S1[0] = = S2[1] && s1[1] = = S2[0])
3. If s1.length = = S2.length = = 3, you need to determine
(s1.substring (0, i) = = s2.substring (0, i) && s1.substring (i) = = s2.substring (i)) | |
(s1.substring (0, i) = = S2.substring (s2.length ()-i) && s1.substring (i) = = s2.substring (0, S2.length ()-i))
It takes more time to rely on the above judgments, so you need to add additional criteria to reduce the number of recursion.
For this problem, the necessary condition is that the S1 is the same length as the S2, and the S1 is the same as the S2 character set.
The code is as follows:
Public Booleanisscramble (string s1, string s2) {if(S1.length ()! =s2.length ()) { return false; } if(s1.length () = = 1) { returns1.equals (S2); } intCharset[] =New int[26]; for(inti=0; I<s1.length (); i++) {Charset[s1.charat (i)-' A ']++; Charset[s2.charat (i)-' A ']--; } for(inti=0; i<26; i++) { if(charset[i]! = 0) return false; } for(intI=1; I<s1.length (); i++) { Booleanresult = (isscramble (s1.substring (0, I), s2.substring (0, i)) &&isscramble (s1.substring (i), s2.substring (i)))||(Isscramble (s1.substring (0, I), s2.substring (S2.length ()-i) &&isscramble (s1.substring (i), s2.substring (0, S2.length ()-i))); if(Result) {return true; } } return false; }
For the subject, it is also possible to improve the efficiency by the solution of dynamic programming. will be updated later.
LeetCode-87 Scramble String