问题描述
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.
问题分析
在构造scrambled string的时候是将二叉树的非叶子节点的两棵子树交换,那么,1、在构造某节点的子树时的分叉点是随机的,即子字符串的长度不定;2、二叉树中的交换子树的节点是随机的,即是否交换是不定的。
定义状态dp[i][j][k]表示string1的i到i+k-1与string2的j到j+k-1是对应的。因此有状态转移方程:
dp[i][j][k]||=dp[i][j][l]&&dp[i+l][j+l][k-l]||dp[i][j+k-l][l]&&dp[i+l][j+k][k-l],其中0 < l < k.
状态转移方程则描述了上面两个条件:1、l表示不同的子字符串的长度;2、或符号左右两边分表表示不交换左右子树和交换左右子树两种情况。
代码如下:
public boolean isScramble(String s1, String s2) {
if(s1==null||s1.length()==0)
return true;
int n=s1.length();
boolean [][][]dp=new boolean[n][n][n+1];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(s1.charAt(i)==s2.charAt(j))
dp[i][j][1]=true;
for(int k=2;k<=n;k++){
for(int i=0;i<=n-k;i++){
for(int j=0;j<=n-k;j++){
for(int l=1;l<k;l++)
dp[i][j][k]=dp[i][j][k]||dp[i][j][l]&&dp[i+l][j+l][k-l]||dp[i][j+k-l][l]&&dp[i+l][j][k-l];
}
}
}
return dp[0][0][n];
}