97. Interleaving String

Posted yaoyudadudu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了97. Interleaving String相关的知识,希望对你有一定的参考价值。

问题描述:

 

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

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

 

解题思路:

一开始我想用dfs,若当前s3的首字符能与s1的匹配,则匹配s1.substr(1) , s2, s3.substr(1)

若不成功则检查s3能否与s2匹配,若能则匹配s1, s2.substr(1), s3

超时了:)超时了!!!!!!!!!!!!我就知道hard没有这么简单啊朋友们TAT

 

遇到这样的字符匹配的题可以考虑dp

类似题目:72. Edit Distance

dp[i][j]表示s1前i个字符和s2前j个字符能否插入式构成 s3 前 i+j 个字符串

初始化:

当i = 0, j = 0 时,代表前0个字符串,所以一定为true

dp[i][0] = dp[i-1][0] && (s1[i-1] == s3[i-1])

dp[0][i] = dp[0][i-1] && (s2[i-1] == s3[i-1])

状态转移方程:

dp[i][j] = (dp[i-1][j] && s1[i-1] == s3[i-1] ) || (dp[i][j-1] && s1[j-1] == s3[j-1])

最后返回dp[len1][len2]

代码:

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

 

以上是关于97. Interleaving String的主要内容,如果未能解决你的问题,请参考以下文章

97. Interleaving String

97. Interleaving String

97. Interleaving String

[leetcode-97-Interleaving String]

97. Interleaving String

[Leetcode] 97. Interleaving String