关闭

LeetCode:Interleaving String

标签: LeetCodeInterleaving String
505人阅读 评论(0) 收藏 举报
分类:

Interleaving String




Total Accepted: 50191 Total Submissions: 221528 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";


其状态转移过程为:

   0 1 2 3 4 5 6 7 8 10

s3 a a d b b c b c a c

-----------------------

     0 1 2 3 4 5

    s1 a a b c c

0 s2 T T T F F F

1 d  F F T T F F

2 b  F F T T T F

3 b  F F T F T T 

4 c  F F T T T F

5 a  F F F F T T


状态转移方程为:

if i==0 dp[i][j] = dp[i][j-1] && s1[j-1]==s3[i+j-1];

if j==0 dp[i][j] = dp[i-1][j] && s2[i-1]==s3[i+j-1];

else dp[i][j] = (dp[i][j-1] && s1[j-1]==s3[i+j-1]) || (dp[i-1][j] && s2[i-1]==s3[i+j-1]) .


c++ code:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        
        int len1 = s1.length();
        int len2 = s2.length();
        if(s3.length() != len1 + len2) return false;
        
        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];
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:348197次
    • 积分:6377
    • 等级:
    • 排名:第3999名
    • 原创:314篇
    • 转载:1篇
    • 译文:0篇
    • 评论:25条
    博客专栏
    最新评论