首页 > 代码库 > LeetCode:Interleaving String

LeetCode:Interleaving String

     Given s1, s2,s3, find whether s3 is formed by the interleaving of s1 ands2.


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];
    }
};