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.
1. True if two substring are equal
2. True if two substring have a point in the middle, the substrings on the left is a scramble string, and the substrings on the right is also scramble string;
3. If two substring in the middle of a certain point, S1 left of substring and S2 to the right of substring for scramble string, while S1 right substring and S2 to the left of substring also scramble String, or True
1 classSolution {2 Public:3 BOOLIsscramble (stringS1,stringS2) {4 5 intn=s1.length ();6vector<vector<vector<BOOL>>> DP (n,vector<vector<BOOL>> (n,vector<BOOL> (n+1)));7 //Dp[i][j][k] represent whether s1[i,i+1,..., I+k-1] and s2[j,j+1,..., j+k-1] is scramble8 9 Ten for(inti=n-1; i>=0; i--) One { A for(intj=n-1; j>=0; j--) - { - for(intk=1; K<=n-max (i,j); k++) the { - if(S1.substr (i,k) = =s2.substr (j,k)) - { -dp[i][j][k]=true; + } - Else + { A for(intL=1; l<k;l++) at { - if(dp[i][j][l]&&dp[i+l][j+l][k-l]| | dp[i][j+k-l][l]&&dp[i+l][j][k-l]) - { -dp[i][j][k]=true; - Break; - } in } - to } + } - } the * } $ returndp[0][0][n];Panax Notoginseng } -};
"Leetcode" Scramble String