# Hard-题目17：87. Scramble String

193人阅读 评论(0)

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

（1） s1==s2.
（2） 存在i，使得s1的前i个字符和s2的前i个字符是scramble，后半部分也是scramble。（相当于左子树和右子树不用调换）
（3） 存在i，使得s1的前i个字符和s2的后i个字符是scramble，s1的后半部分和s2的前半部分是scramble。（相当于从第i个点处把s1拆开，再交换左右子树。）

public class Solution {
public boolean isScramble(String s1, String s2) {
int len1 = s1.length(),len2 = s2.length();
if(len1 != len2)
return false;
else if(len1==1)
return s1.charAt(0)==s2.charAt(0);
else if(s1.equals(s2))
return true;
else {
char[] ca1 = s1.toCharArray(),ca2 = s2.toCharArray();
Arrays.sort(ca1);
Arrays.sort(ca2);
for(int i = 0;i<len1;i++)
if(ca1[i]!=ca2[i])
return false;
boolean result = false;
for(int i = 1;i<len1;i++) {
String s11 = s1.substring(0, i);
String s12 = s1.substring(i);
String s21 = s2.substring(0, i);
String s22 = s2.substring(i);
String s23 = s2.substring(0,len2-i);
String s24 = s2.substring(len2-i);
if(isScramble(s11,s21)&&isScramble(s12,s22) || (isScramble(s11,s24)&&isScramble(s12,s23))) {
result = true;
break;
}
}
return result;
}
}
}

7ms,beats 54.91%，众数4ms,21.84%
Cmershen的碎碎念：

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：55996次
• 积分：3198
• 等级：
• 排名：第10679名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：7条
文章分类
最新评论