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

[LeetCode] Interleaving String(dp)

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

标签:style   blog   color   io   for   div   amp   log   

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)

标签:style   blog   color   io   for   div   amp   log   

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

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