首页 > 其他 > 详细

Interleaving String

时间:2016-09-24 12:14:49      阅读:170      评论:0      收藏:0      [点我收藏+]

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 l1 = s1.length();
        int l2 = s2.length();
        int l3 = s3.length();
        
        if(l3 != (l1+l2))
            return false;
        
        bool dp[l1+1][l2+1];
        for(int i=0;i<l1+1;i++){
            for(int j=0;j<l2+1;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[l1][l2];
    }
};

 

Interleaving String

原文:http://www.cnblogs.com/wxquare/p/5902768.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!