码迷,mamicode.com
首页 > 其他好文 > 详细

Interleaving String

时间:2014-12-03 21:08:49      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

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.

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int n1 = s1.length(), n2 = s2.length(), n3 = s3.length();
        if (n1+n2 != n3) return false;

        vector<vector<bool>> V(n1+1, vector<bool>(n2+1, false));

        V[n1][n2] = (s3[n1+n2]==\0);

        // fill bottom
        for (int j=n2-1; j>=0; j--) V[n1][j]  = (s2[j]==s3[n1+j] && V[n1][j+1]);

        // fill right
        for (int i=n1-1; i>=0; i--) V[i][n2] = (s1[i]==s3[n2+i] && V[i+1][n2]);

        // fill DP table from bottom right
        for (int j=n2-1; j>=0; j--){
            for (int i=n1-1; i>=0; i--){
                V[i][j] = (s1[i]==s3[i+j] && V[i+1][j]) | (s2[j]==s3[i+j] && V[i][j+1]);
            }
        }
        return V[0][0];
    }
};

 

Interleaving String

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/code-swan/p/4141178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!