[leetcode]scramble string

题目描述

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”:

1
2
3
4
5
6
7
    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”.

1
2
3
4
5
6
7
    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”.

1
2
3
4
5
6
7
    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.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class  {
public boolean isScramble(String s1, String s2) {
int len1 = s1.length(), len2 = s2.length();
if(len1 != len2) return false;
if(len1 == 0) return true;

if(s1.equals(s2)) return true;
//假设只有ASCII字符
int[] letters = new int[256];

//两个字符串的出现的字符以及每个字符出现的次数都要一样,否则为false
for(int i = 0; i < len1; i++){
letters[s1.charAt(i)]++;
letters[s2.charAt(i)]--;
}

for(int i = 0; i < len1; i++){
if(letters[s1.charAt(i)] != 0) return false;
}
//i从0开始,stackoverflow
for(int i = 1; i < len1; i++){
if(isScramble(s1.substring(0, i), s2.substring(0,i)) && isScramble(s1.substring(i), s2.substring(i))) return true;
if(isScramble(s1.substring(0, i), s2.substring(len2 - i)) && isScramble(s1.substring(i), s2.substring(0,len2-i))) return true;
}

return false;
}
}