首页 > 其他 > 详细

[LeetCode] Interleaving String(dp)

时间:2014-08-06 22:44:32      阅读:368      评论:0      收藏:0      [点我收藏+]

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.

分析:非常好的DP的训练题,用dp矩阵存储的元素(i,j)表示s1中前i个元素,s2中前j个元素与s3中前i+j个元素相匹配

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int len1 = s1.size(),len2 = s2.size(),len3 = s3.size();
        if(len1+len2 != len3)
            return false;
        vector<bool> temp(len2+1,false);
        vector<vector<bool> > dp(len1+1,temp);//(i,j)表示s1中前i个元素,s2中前j个元素与s3中前i+j个元素相匹配

        for(int i=0;i<=len1;i++){
            for(int j=0;j<=len2;j++){
                if(i==0 && j==0){
                   dp[i][j]=true;
                   continue;
                }
                if(i>0 && s1[i-1]==s3[i+j-1] && dp[i-1][j]==true)
                    dp[i][j]=true;
                if(j>0 && s2[j-1]==s3[i+j-1] && dp[i][j-1]==true)
                    dp[i][j]=true;
            
            
            }//end for
        
        }//end for

       return dp[len1][len2];
    
    }
};

 

[LeetCode] Interleaving String(dp),布布扣,bubuko.com

[LeetCode] Interleaving String(dp)

原文:http://www.cnblogs.com/Xylophone/p/3895724.html

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