97. Interleaving String (String; DP)

Given s1, s2, s3, 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.

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        //dp[i][j]: s3[i+j-1] can be interleaved by s1[0..i], s2[0..j]
        //dp[i][j] = dp[i-1][j] if s3[i+j-1]==s1[i]
        //            = dp[i][j-1] if s3[i+j-1]==s2[j]
        //so traverse i,j,k from small to large
        int len1 = s1.length();
        int len2 = s2.length();
        if(len1+len2!=s3.length()) return false;
        vector<vector<bool>> dp(len1+1, vector<bool>(len2+1, false));
        
        //initial status
        dp[0][0] = true; //0 means null string
        for(int j = 1; j <= len2; j++){
            dp[0][j] = dp[0][j-1] && s2[j-1]==s3[j-1];
        }
        for(int i = 1; i <= len1; i++){
            dp[i][0] = dp[i-1][0] && s1[i-1]==s3[i-1];
        }
        
        //state transfer
        for(int i = 1; i<= len1; i++){
            for(int j = 1; j <= len2; j++){
                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];
    }
};

 

posted on 2015-10-29 08:25  joannae  阅读(161)  评论(0编辑  收藏  举报

导航