1+ Given a string s1 , we may represent it as a binary tree by partitioning it to two non -empty substrings recursively .
2+
3+ Below is one possible representation of s1 = "great" :
4+
5+ great
6+ / \
7+ gr eat
8+ / \ / \
9+ g r e at
10+ / \
11+ a t
12+ To scramble the string , we may choose any non -leaf node and swap its two children .
13+
14+ For example , if we choose the node "gr" and swap its two children , it produces a scrambled string "rgeat" .
15+
16+ rgeat
17+ / \
18+ rg eat
19+ / \ / \
20+ r g e at
21+ / \
22+ a t
23+ We say that "rgeat" is a scrambled string of "great" .
24+
25+ Similarly , if we continue to swap the children of nodes "eat " and "at ", it produces a scrambled string "rgtae ".
26+
27+ rgtae
28+ / \
29+ rg tae
30+ / \ / \
31+ r g ta e
32+ / \
33+ t a
34+ We say that "rgtae" is a scrambled string of "great" .
35+
36+ Given two strings s1 and s2 of the same length , determine if s2 is a scrambled string of s1 .
37+
38+ public class Solution {
39+ public boolean isScramble (String s1 , String s2 ) {
40+ int length1 = s1 .length ();
41+ int length2 = s2 .length ();
42+ if (length1 != length2 )
43+ return false ;
44+
45+ if (length1 == 0 || s1 .equals (s2 ))
46+ return true ;
47+
48+ char [] ca1 = s1 .toCharArray ();
49+ char [] ca2 = s2 .toCharArray ();
50+ Arrays .sort (ca1 );
51+ Arrays .sort (ca2 );
52+ if (!Arrays .equals (ca1 , ca2 ))
53+ return false ;
54+
55+ int i = 1 ;
56+ while (i < length1 ) {
57+ String a1 = s1 .substring (0 , i );
58+ String b1 = s1 .substring (i , length1 );
59+ String a2 = s2 .substring (0 , i );
60+ String b2 = s2 .substring (i , length2 );
61+ if (a1 .equals (b2 ) && b1 .equals (a2 )) return true ;
62+ boolean r = isScramble (a1 , a2 ) && isScramble (b1 , b2 );
63+ if (!r ) {
64+ String c2 = s2 .substring (0 , length1 - i );
65+ String d2 = s2 .substring (length1 - i );
66+ r = isScramble (a1 , d2 ) && isScramble (b1 , c2 );
67+ }
68+ if (r ) return true ;
69+ i ++;
70+ }
71+ return false ;
72+ }
73+ }
0 commit comments