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

LeetCode:Interleaving String

时间:2016-05-27 11:31:42      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

Interleaving String




Total Accepted: 49969 Total Submissions: 220816 Difficulty: Hard

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.

Subscribe to see which companies asked this question





















思路:

s1 = "aabcc";

s2 = "dbbca";

s3 = "aadbbcbcac";


1)如果i==0 && j==0,dp[0][0] = true;

2)如果i==0,判断s2[j]==s3[i+j] 并且 dp[i][j-1]==true,则dp[i][j] = true;

3)如果j==0,与2)类似;

4)如果i != 0 && j != 0,判断(dp[i][j-1] && s2[j]==s3[i+j]) || (dp[i-1][j] && s1[i]==s3[i+j]);

5)dp[s1.length()][s2.length()]即为结果。


过程如下图所示:



j 0  1   2   3   4   5 
 i 
s2 d b b c a
 0  s1 T F F F F F
 1  a T F F F F F
 2  a T T T T T F
 3  b F T T F T F
 4  c F F T T T T
 5  c F F F T F T


c++ code:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int len1 = s1.length();
        int len2 = s2.length();
        bool dp[len1+1][len2+1];
        
        for(int i=0;i<=len1;i++) {
            for(int j=0;j<=len2;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[len1][len2];
    }
};


LeetCode:Interleaving String

标签:

原文地址:http://blog.csdn.net/itismelzp/article/details/51505419

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