Skip to content

Commit 0f6efa5

Browse files
committed
rewrite
1 parent 15b648d commit 0f6efa5

File tree

1 file changed

+22
-32
lines changed

1 file changed

+22
-32
lines changed

ScrambleString.java

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
2-
3-
import java.util.Arrays;
4-
51
/**
62
* Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
73
*
@@ -43,39 +39,33 @@
4339

4440
public class ScrambleString {
4541
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())
4943
return false;
50-
51-
if (length1 == 0 || s1.equals(s2))
44+
if (s1.equals(s2))
5245
return true;
5346

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+
}
6051

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;
7864
}
7965
return false;
8066
}
67+
68+
public static void main(String[] args) {
69+
System.out.println(new ScrambleString().isScramble("aab", "bab"));
70+
}
8171
}

0 commit comments

Comments
 (0)