【leetcode】Scramble String

时间:2022-05-29 11:39:26

Scramble String

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.

1. 如果两个substring相等的话,则为true
2. 如果两个substring中间某一个点,左边的substrings为scramble string, 同时右边的substrings也为scramble string,则为true
3. 如果两个substring中间某一个点,s1左边的substring和s2右边的substring为scramble string, 同时s1右边substring和s2左边的substring也为scramble string,则为true
 class Solution {
public:
bool isScramble(string s1, string s2) { int n=s1.length();
vector<vector<vector<bool>>> dp(n,vector<vector<bool>>(n,vector<bool>(n+)));
//dp[i][j][k] represent whether s1[i,i+1,...,i+k-1] and s2[j,j+1,...,j+k-1] is scramble for(int i=n-;i>=;i--)
{
for(int j=n-;j>=;j--)
{
for(int k=;k<=n-max(i,j);k++)
{
if(s1.substr(i,k)==s2.substr(j,k))
{
dp[i][j][k]=true;
}
else
{
for(int l=;l<k;l++)
{
if(dp[i][j][l]&&dp[i+l][j+l][k-l]||dp[i][j+k-l][l]&&dp[i+l][j][k-l])
{
dp[i][j][k]=true;
break;
}
} }
}
} }
return dp[][][n];
}
};