LeetCode:Interleaving String

来源:互联网 发布:哪里有卖呼死你软件 编辑:程序博客网 时间:2024/04/28 19:18

Interleaving String




Total Accepted: 49969 Total Submissions: 220816 Difficulty: Hard

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.

Subscribe to see which companies asked this question

Hide Tags
 Dynamic Programming String




















思路:

s1 = "aabcc";

s2 = "dbbca";

s3 = "aadbbcbcac";


1)如果i==0 && j==0,dp[0][0] = true;

2)如果i==0,判断s2[j]==s3[i+j] 并且 dp[i][j-1]==true,则dp[i][j] = true;

3)如果j==0,与2)类似;

4)如果i != 0 && j != 0,判断(dp[i][j-1] && s2[j]==s3[i+j]) || (dp[i-1][j] && s1[i]==s3[i+j]);

5)dp[s1.length()][s2.length()]即为结果。


过程如下图所示:



j0 1  2  3  4  5  i 
s2dbbca 0 s1TFFFFF 1 aTFFFFF 2 aTTTTTF 3 bFTTFTF 4 cFFTTTT 5 cFFFTFT


c++ code:

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


0 0
原创粉丝点击