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 swap its-children, it produces a scrambled string < Code style= "Font-family:menlo,monaco,consolas, ' Courier New ', monospace; font-size:12.6000003814697px; PADDING:2PX 4px; Color:rgb (199,37,78); Background-color:rgb (249,242,244) ">" 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 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 .
Test instructions: asks if S2 is a split string of S1.
Idea: One is recursive search, each time is a string into the length of I and len-i two to wear, and then cross-compare; the second is DP, set DP[LEN][I][J] represents the length of Len at the beginning of the S1 the first position of the S2 J position of the start of Len is satisfied with the condition.
public class Solution {public Boolean isscramble (string s1, string s2) { int len1 = S1.length (); int len2 = S2.length (); if (len1! = Len2) return false; if (len1 = = 1) return s1.equals (S2); Char str1[] = S1.tochararray (); Char str2[] = S2.tochararray (); Arrays.sort (STR1); Arrays.sort (STR2); if (Arrays.equals (str1, str2) = = false) return false; for (int i = 1; i < len1; i++) { String S11 = s1.substring (0, i); String S12 = s1.substring (i, len1); String S21 = s2.substring (0, i); String S22 = s2.substring (i, len1); if (isscramble (S11, S21) && isscramble (S12, S22)) return true; S21 = s2.substring (0, len1-i); S22 = s2.substring (len1-i, len1); if (isscramble (S11, S22) && isscramble (S12, S21)) return true; } return false; }}
public class Solution {public Boolean isscramble (string s1, string s2) { int len = S1.length (); if (len! = S2.length ()) return false; if (len = = 0) return false; Char c1[] = S1.tochararray (); Char c2[] = S2.tochararray (); Boolean dp[][][] = new boolean[len+1][len+1][len+1]; for (int i = 0, i < len; i++) for (int j = 0; J < Len; j + +) dp[1][i][j] = c1[i] = = C2[j]; for (int k = 2, k <= Len; k++) for (int i = len-k, i >= 0; i--) for (int j = len-k; J >= 0; j--) {
boolean flag = false; for (int m = 1; M <= k &&!flag; m++) { flag = (Dp[m][i][j] && dp[k-m][i+m][j+m]) | | (Dp[m][i][j+k-m] && dp[k-m][i+m][j]); } DP[K][I][J] = flag; } return dp[len][0][0];} }
Leetcode Scramble String