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.
Solution:
1 public class Solution { 2 public boolean isScramble(String s1, String s2) { 3 if(s1.equals(s2)) 4 return true; 5 int l1=s1.length(); 6 int l2=s2.length(); 7 if(l1!=l2) 8 return false; 9 if(l1==0) 10 return true; 11 if(l1==1) 12 return s1.equals(s2); 13 char[] c_s1=s1.toCharArray(); 14 char[] c_s2=s2.toCharArray(); 15 Arrays.sort(c_s1); 16 Arrays.sort(c_s2); 17 for(int i=0;i<c_s1.length;++i){ 18 if(c_s1[i]!=c_s2[i]) 19 return false; 20 } 21 boolean b=false; 22 for(int i=1;i<l1&&!b;++i){ 23 String s11=s1.substring(0,i); 24 String s12=s1.substring(i); 25 String s21=s2.substring(0,i); 26 String s22=s2.substring(i); 27 b=isScramble(s11, s21)&&isScramble(s12, s22); 28 if(!b){ 29 String s31=s2.substring(0, l1-i); 30 String s32=s2.substring(l1-i); 31 b=isScramble(s11, s32)&&isScramble(s12, s31); 32 } 33 } 34 return b; 35 } 36 }
------------------------------------------------------------------------------------
20150220:
1 public class Solution { 2 public boolean isScramble(String s1, String s2) { 3 if(s1==null||s2==null||s1.length()!=s2.length()) 4 return false; 5 if(s1.equals(s2)) 6 return true; 7 char[] c1=s1.toCharArray(); 8 char[] c2=s2.toCharArray(); 9 Arrays.sort(c1); 10 Arrays.sort(c2); 11 for(int i=0;i<c1.length;++i){ 12 if(c1[i]!=c2[i]) 13 return false; 14 } 15 int N=s1.length(); 16 for(int i=1;i<N;++i){ 17 String s1_temp1=s1.substring(0,i); 18 String s1_temp2=s1.substring(i); 19 String s2_temp1=s2.substring(0,i); 20 String s2_temp2=s2.substring(i); 21 if(isScramble(s1_temp1, s2_temp1)&&isScramble(s1_temp2, s2_temp2)) 22 return true; 23 String s2_temp3=s2.substring(0,N-i); 24 String s2_temp4=s2.substring(N-i); 25 if(isScramble(s1_temp1, s2_temp4)&&isScramble(s1_temp2, s2_temp3)) 26 return true; 27 } 28 return false; 29 } 30 }