题目
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.
将一个单词任意划分,构成任意棵树,交换任意位置;
如果可以构成后面的单词则称之为scramble。
可以注意到,在任意位置对数组进行划分后,无论如何交换,前后部分必然是分割开的。
对于这类问题dp。
通过一个flag[i][j][k]记录从s1[i]、s2[j]开始的两个长为k的序列是否是scramble。
由s1[i]、s2[j]开始的两个长为k的序列scramble的递归判断为:
1、flag[i][j][l]为true,且flag[i][j][k-l]为true,(l<=k,即前后有两个子串分别scramble)
或者
2、flag[i][j+k-l][l]为true,且flag[i+l][j][k-l]为true(即有交换后前后两个子串分别scramble)
自底向上dp即可。
代码:
class Solution {
public:
bool isScramble(string s1, string s2) {
if(s1.size()!=s2.size()) //先判断长度
return false;
int len=s1.size();
bool ***flag=new bool** [len]; //flag[i][j][k]表示从s1[i]、s2[j]开始的长度为k的序列是否符合要求
for(int i=0;i<len;i++) //初始化
{
flag[i]=new bool * [len];
for(int j=0;j<len;j++)
{
flag[i][j]=new bool [len+1];
for(int k=0;k<=len;k++)
flag[i][j][k]=false;
}
}
for(int k=1;k<=len;k++) //dp
for(int i=0;i<=len-k;i++)
for(int j=0;j<=len-k;j++)
if(k==1) //长度为1时判断是否相等
flag[i][j][k]=s1[i]==s2[j];
else //否则判断在任意位置断开后,前后部分是否都是scramble,或者交换后是scramble的
for(int l=1;l<k;l++)
if((flag[i][j][l]&&flag[i+l][j+l][k-l])||(flag[i][j+k-l][l]&&flag[i+l][j][k-l]))
{
flag[i][j][k]=true;
break;
}
return flag[0][0][len];
}
};
本文介绍了一种用于判断字符串是否可以通过乱序匹配成为另一个字符串的方法。通过深度优先搜索(DFS)策略,实现了一个O(n^3)的时间复杂度算法。详细解释了算法的核心思想、实现步骤,并提供了代码示例。
399

被折叠的 条评论
为什么被折叠?



