LeetCode | Interleaving String

题目:

Given s1s2s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

思路:

利用动态规划去完成。当dp[i][j][k]表示S1取第i位,S2取第j位,S3取第k位时是否能够满足条件。递归条件是 1)S1[i]==S3[k]时,dp[i][j][k]=dp[i-1][j][k-1] 2)S2[j]==S3[k]时,dp[i][j][k]=dp[i][j-1][k-1] 3)S1[i]==S2[j]==S3[k]时,dp[i][j][k]=dp[i-1][j][k-1] | dp[i][j-1][k-1]

备注,代码中的存储空间未优化。

代码:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        if(s1.size()+s2.size()!=s3.size())
        {
            return false;
        }
        else
        {
            bool*** dp = new bool**[s1.size()+1];
            for(int i=0;i<=s1.size();i++)
            {
                dp[i] = new bool*[s2.size()+1];
                for(int j=0;j<=s2.size();j++)
                {
                    dp[i][j] = new bool[s3.size()+1];
                }
            }
            
            for(int i=0;i<=s1.size();i++)
            {
                for(int j=0;j<=s2.size();j++)
                {
                    if(i==0&&j==0)
                    {
                        dp[i][j][i+j] = true;
                        continue;
                    }
                    dp[i][j][i+j] = false;
                    if(i>0&&s1[i-1]==s3[i+j-1])
                    {
                        dp[i][j][i+j] |= dp[i-1][j][i+j-1];
                    }
                    if(j>0&&s2[j-1]==s3[i+j-1])
                    {
                        dp[i][j][i+j] |= dp[i][j-1][i+j-1];
                    }
                }
            }
            return dp[s1.size()][s2.size()][s3.size()];
        }
    }
};

递归方法,思路简单但时间复杂度太高

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        return interleave(s1, s2, s3, 0, 0);
    }
    
    bool interleave(string &s1, string &s2, string &s3, int i1, int i2) {
        if(i1 + i2 == s3.size() && i1 == s1.size() && i2 == s2.size()){
            return true;
        }
        
        bool m1 = false;
        if(i1 < s1.size() && s1[i1] == s3[i1+i2]){
            m1 = interleave(s1, s2, s3, i1+1, i2);
        }
        
        bool m2 = false;
        if(i2 < s2.size() && s2[i2] == s3[i1+i2]){
            m2 = interleave(s1, s2, s3, i1, i2+1);
        }
        
        return m1 || m2;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17509247
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞