LeetCode| 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)s1左侧与s2左侧比较,s1右侧与s2右侧比较 2)s1左侧与s2右侧比较,s1右侧与s2左侧比较

为了简化计算量,我们可以用动态规划的方法来完成。dp[l][i][j]中的l+1代表子字符串的长度,i代表s1的起始点,j代表s2的起始点。

代码:

class Solution {
public:
    bool isScramble(string s1, string s2) {
        
        if(s1.size()!=s2.size())
        {
            return false;
        }
        else
        {
            int len = s1.size();
            bool*** dp = new bool**[len];
            for(int i=0;i<len;i++)
            {
                dp[i]=new bool*[len];
                for(int j=0;j<len;j++)
                {
                    dp[i][j]=new bool[len];
                }
            }
            
            for(int i=0;i<len;i++)
            {
                for(int j=0;j<len;j++)
                {
                    dp[0][i][j]=(s1[i]==s2[j]);
                }
            }
            
            for(int l=2;l<=len;l++)
            {
                for(int i=0;i+l<=len;i++)
                {
                    for(int j=0;j+l<=len;j++)
                    {
                        dp[l-1][i][j] = false;
                        for(int k=1;k<=l-1;k++)
                        {
                            if(dp[k-1][i][j]&&dp[l-k-1][i+k][j+k])
                            {
                                dp[l-1][i][j]=true;
                            }
                            else if(dp[k-1][i][j+l-k]&&dp[l-k-1][i+k][j])
                            {
                                dp[l-1][i][j]=true;
                            }
                        }
                    }
                }
            }
            
            return dp[len-1][0][0];
        }
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17715633
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞