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

LeetCode:Interleaving String

时间:2014-06-26 10:10:19      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   strong   2014   

     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.


解题思路:


    如果熟悉动态规划的LCS和ED问题的话,不难看出这是个dp题目.首先,我们定义如下状态:


dp[i+1][j+1]:表示s1[0...i]与s2[0...j]能否交替形成s3[0...i+j+1]部分.


状态转移方程:

    dp[i+1][j+1] = (dp[i][j+1] && s1[i] == s3[i+j+1]) | (dp[i+1][j] && s2[j] == s3[i+j+1]);


解题代码:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) 
    {
        int m = s1.size(), n = s2.size();
        if (m + n != s3.size())
            return false;
        bool dp[m+1][n+1];
        dp[0][0] = true;
        //初始化边界.
        for (int i = 0; i < n; ++i)
            dp[0][i+1] = dp[0][i] && s2[i] == s3[i];
        for (int i = 0; i < m; ++i)
            dp[i+1][0] = dp[i][0] && s1[i] == s3[i];
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                dp[i+1][j+1] = (dp[i][j+1] && s1[i] == s3[i+j+1]) | (dp[i+1][j] && s2[j] == s3[i+j+1]);
        return dp[m][n];
    }
};



LeetCode:Interleaving String,布布扣,bubuko.com

LeetCode:Interleaving String

标签:style   class   blog   code   strong   2014   

原文地址:http://blog.csdn.net/dream_you_to_life/article/details/34433139

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