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.
思路:对于s1,s2, 他们scramble的条件是a)或者scramble(s1[0, i) s2[0,i)) && scramble(s1[i, length), s2[i, length))
b)或者scramble(s1[0, i) s2[length-i, length)) && scramble(s1[i, length), s2[0, length-i))
递归:如果不提前计算anagram会超时:O(4^n)
public boolean isScramble(String s1, String s2) {
if (s1 == null || s2 == null || s1.length() != s2.length()) {
return false;
}
if (s1.equals(s2)) {
return true;
}
int[] a = new int[26];
for (int i = 0; i < s1.length(); i++) {
a[(int)(s1.charAt(i) - 'a')]++;
}
for (int i = 0; i < s2.length(); i++) {
a[(int)(s2.charAt(i) - 'a')]--;
if(a[(int)(s2.charAt(i) - 'a')] < 0) {
return false;
}
}
for (int i = 1; i < s1.length(); 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(s2.length()-i))
&& isScramble(s1.substring(i), s2.substring(0, s2.length()-i))) {
return true;
}
}
return false;
}
三维DP暂时理解不太清楚,作为参考:http://blog.csdn.net/linhuanmars/article/details/24506703
public boolean isScramble(String s1, String s2) {
if(s1==null || s2==null || s1.length()!=s2.length())
return false;
if(s1.length()==0)
return true;
boolean[][][] res = new boolean[s1.length()][s2.length()][s1.length()+1];
for(int i=0;i<s1.length();i++)
{
for(int j=0;j<s2.length();j++)
{
res[i][j][1] = s1.charAt(i)==s2.charAt(j);
}
}
for(int len=2;len<=s1.length();len++)
{
for(int i=0;i<s1.length()-len+1;i++)
{
for(int j=0;j<s2.length()-len+1;j++)
{
for(int k=1;k<len;k++)
{
res[i][j][len] |= res[i][j][k]&&res[i+k][j+k][len-k] || res[i][j+len-k][k]&&res[i+k][j][len-k];
}
}
}
}
return res[0][0][s1.length()];
}