1
-
2
-
3
- import java .util .Arrays ;
4
-
5
1
/**
6
2
* Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
7
3
*
43
39
44
40
public class ScrambleString {
45
41
public boolean isScramble (String s1 , String s2 ) {
46
- int length1 = s1 .length ();
47
- int length2 = s2 .length ();
48
- if (length1 != length2 )
42
+ if (s1 .length () != s2 .length ())
49
43
return false ;
50
-
51
- if (length1 == 0 || s1 .equals (s2 ))
44
+ if (s1 .equals (s2 ))
52
45
return true ;
53
46
54
- char [] ca1 = s1 .toCharArray ();
55
- char [] ca2 = s2 .toCharArray ();
56
- Arrays .sort (ca1 );
57
- Arrays .sort (ca2 );
58
- if (!Arrays .equals (ca1 , ca2 ))
59
- return false ;
47
+ int [] A = new int [26 ];
48
+ for (int i = 0 ; i < s1 .length (); i ++) {
49
+ ++A [s1 .charAt (i ) - 'a' ];
50
+ }
60
51
61
- int i = 1 ;
62
- while (i < length1 ) {
63
- String a1 = s1 .substring (0 , i );
64
- String b1 = s1 .substring (i , length1 );
65
- String a2 = s2 .substring (0 , i );
66
- String b2 = s2 .substring (i , length2 );
67
- if (a1 .equals (b2 ) && b1 .equals (a2 ))
68
- return true ;
69
- boolean r = isScramble (a1 , a2 ) && isScramble (b1 , b2 );
70
- if (!r ) {
71
- String c2 = s2 .substring (0 , length1 - i );
72
- String d2 = s2 .substring (length1 - i );
73
- r = isScramble (a1 , d2 ) && isScramble (b1 , c2 );
74
- }
75
- if (r )
76
- return true ;
77
- i ++;
52
+ for (int j = 0 ; j < s2 .length (); j ++) {
53
+ --A [s2 .charAt (j ) - 'a' ];
54
+ }
55
+
56
+ for (int k = 0 ; k < 26 ; k ++) {
57
+ if (A [k ] != 0 ) return false ;
58
+ }
59
+
60
+ for (int i = 1 ; i < s1 .length (); i ++) {
61
+ boolean result = isScramble (s1 .substring (0 , i ), s2 .substring (0 , i )) && isScramble (s1 .substring (i ), s2 .substring (i ));
62
+ result = result || (isScramble (s1 .substring (0 , i ), s2 .substring (s2 .length () - i , s2 .length ())) && isScramble (s1 .substring (i ), s2 .substring (0 , s2 .length () - i )));
63
+ if (result ) return true ;
78
64
}
79
65
return false ;
80
66
}
67
+
68
+ public static void main (String [] args ) {
69
+ System .out .println (new ScrambleString ().isScramble ("aab" , "bab" ));
70
+ }
81
71
}
0 commit comments