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.
参考了CSDN博客 http://blog.csdn.net/pickless/article/details/11501443。
定义F[i][j][k],
当F[i][j][k]=true时,表示S1[i..i+k-1] == S2[j..j+k-1]。
用白话表达:F[i][j][k]记录的是S1从i开始k个字符与S2从j开始k个字符是否为Scramble String。
最简单的情况为k=1时,即S1[i]与S2[j]是否为Scramble String。
因此F[i][j][1] = S1[i] == S2[j]。
当K=2时,
F[i][j][2] = (F[i][j][1] && F[i+1][j+1][1]) || (F[i][j+1][1] && F[i+1][j][1])。
F[i][j][1] && F[i+1][j+1][1]表达的是 S1[i] == S2[j] && S1[i+1]==S2[j+1](例如:“AC”和“AC”),如果这个条件满足,那么S1[i..i+1]与S2[j..j+1]自然为Scramble String,即F[i][j][2] = true。
F[i][j+1][1] && F[i+1][j][1]表达的是S1[i+1] == S2[j] && S1[i] == S2[j + 1] (例如: “AB”和“BA”),同样如果该条件满足,F[i][j][2] = true。
当K为更大的数时,同递归算法一样,我们需要枚举分割点,假设左边长度为l,即S[i..i+l-1],右边长度为k-l,即S[i+l..i+k-1]。
同样存在两种情况,S1左 = S2左 && S1右 = S2右 或者 S1左 = S2右 && S1右 = S2左。
public boolean isScramble(String s1, String s2) {
if(s1.equals(s2))
return true;
char[] ch1 = s1.toCharArray();
char[] ch2 = s2.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
if(!new String(ch1).equals(new String(ch2)))
return false;
for(int i=1;i<s1.length();i++)
{
if(isScramble(s1.substring(0,i), s2.substring(0,i))&&isScramble(s1.substring(i,s1.length()), s2.substring(i,s2.length())))
return true;
if(isScramble(s1.substring(0,i),s2.substring(s2.length()-i,s2.length()))&&isScramble(s1.substring(i,s1.length()), s2.substring(0,s2.length()-i)))
return true;
}
return false;
}
public boolean isScramble(String s1, String s2) {
if(s1.length()!=s2.length())
return false;
int len = s1.length();
boolean[][][] scr = new boolean[len][len][len+1];
for(int k=1;k<=len;k++)
{
for(int i=0;i<=len-k;i++)
{
for(int j=0;j<=len-k;j++)
{
if(k==1)
{
scr[i][j][k] = s1.charAt(i)==s2.charAt(j);
}
else
{
for(int l=1;l<k;l++)
{
if((scr[i][j][l]&&scr[i+l][j+l][k-l])||(scr[i][j+l][k-l]&&scr[i+k-l][j][l]))
{
scr[i][j][k] = true;
break;
}
}
}
}
}
}
return scr[0][0][len];
}
}