题目:
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"
.
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
思路:
当看到本题时,非常容易就顺着题目的意思去建立树形结构去了,但其实题目中的真实目的是阐释两个字符串之间的转换关系,
如果真的去建立一棵树进行树的操作转换,可能是相当麻烦的,本题使用递归+剪支 解决。
假设当前两个字符串分别为A和B,则A分为两部分leftA和rightA,同样B也被分为两部分leftB和rightB,则若A、B能够
相互转换,必然遵守:(leftA.length = leftB.length && rightA.length=rightB.length) || (leftA.length=rightB.length && rightA.length=leftB.length)
在每层具体判断的时候,首先判断长度是否相同,不同直接返回false;其次判断是否相等,相等就可以直接返回true。
否则,再去判断对应字母的个数是否相等。若不等直接返回false;如相等,则使用以上遵守条件进行递归的判断,进入下一层。
注意:此处需要进行分割的遍历,即遍历每一个能够分割的位置进行判断。
AC代码:
public boolean isScramble(String s1, String s2) {
int len = s1.length();
if(len!=s2.length())
return false;
if(s1.equals(s2))
return true;
int[] bools = new int[27];
for(char a:s1.toCharArray()){
bools[a-'a']++;
}
for(char b:s2.toCharArray()){
bools[b-'a']--;
}
for(Integer aa:bools)
if(aa!=0)
return false;
for(int i=1;i<len;i++){
if((isScramble(s1.substring(0,i),s2.substring(0,i)) && isScramble(s1.substring(i),s2.substring(i))) ||
(isScramble(s1.substring(0,i),s2.substring(len-i)) && isScramble(s1.substring(i),s2.substring(0,len-i)))){
return true;
}
}
return false;
}