LeetCode:Interleaving String

Interleaving String




Total Accepted: 50191  Total Submissions: 221528  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";


其状态转移过程为:

   0 1 2 3 4 5 6 7 8 10

s3 a a d b b c b c a c

-----------------------

     0 1 2 3 4 5

    s1 a a b c c

0 s2 T T T F F F

1 d  F F T T F F

2 b  F F T T T F

3 b  F F T F T T 

4 c  F F T T T F

5 a  F F F F T T


状态转移方程为:

if i==0 dp[i][j] = dp[i][j-1] && s1[j-1]==s3[i+j-1];

if j==0 dp[i][j] = dp[i-1][j] && s2[i-1]==s3[i+j-1];

else dp[i][j] = (dp[i][j-1] && s1[j-1]==s3[i+j-1]) || (dp[i-1][j] && s2[i-1]==s3[i+j-1]) .


c++ code:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        
        int len1 = s1.length();
        int len2 = s2.length();
        if(s3.length() != len1 + len2) return false;
        
        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];
    }
};


你可能感兴趣的:(LeetCode,String,Interleaving)