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

97. Interleaving String *HARD* -- 判断s3是否为s1和s2交叉得到的字符串

时间:2016-04-20 01:49:47      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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.

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int l1 = s1.size(), l2 = s2.size(), i, j;
        if(l1 + l2 != s3.size())
            return false;
        vector<vector<bool>> isMatch(l1+1, vector<bool>(l2+1, false));
        isMatch[0][0] = true;
        for(i = 1; i <= l1; i++)
        {
            if(s1[i-1] == s3[i-1])
                isMatch[i][0] = true;
            else
                break;
        }
        for(i = 1; i <= l2; i++)
        {
            if(s2[i-1] == s3[i-1])
                isMatch[0][i] = true;
            else
                break;
        }
        for(i = 1; i <= l1; i++)
        {
            for(j = 1; j <= l2; j++)
            {
                isMatch[i][j] = ((s1[i-1] == s3[i+j-1]) && isMatch[i-1][j]) || ((s2[j-1] == s3[i+j-1]) && isMatch[i][j-1]);
            }
        }
        return isMatch[l1][l2];
    }
};

Considering:

s1 = a1, a2 ........a(i-1), ai
s2 = b1, b2, .......b(j-1), bj
s3 = c1, c3, .......c(i+j-1), c(i+j)


Defined

match[i][j] means s1[0..i] and s2[0..j] is matched S3[0..i+j]

So, if ai == c(i+j), then match[i][j] = match[i-1][j], which means

s1 = a1, a2 ........a(i-1)
s2 = b1, b2, .......b(j-1), bj
s3 = c1, c3, .......c(i+j-1)

Same, if bj = c(i+j), then match[i][j] = match[i][j-1];

Formula:

Match[i][j] =
(s3[i+j-1] == s1[i]) && match[i-1][j] ||
(s3[i+j-1] == s2[j]) && match[i][j-1]

Initialization:

i=0 && j=0, match[0][0] = true;

i=0, s3[j] == s2[j], match[0][j] |= match[0][j-1]
s3[j] != s2[j], match[0][j] = false;

j=0, s3[i] == s1[i], match[i][0] |= match[i-1][0]
s3[i] != s1[i], Match[i][0] = false;

97. Interleaving String *HARD* -- 判断s3是否为s1和s2交叉得到的字符串

标签:

原文地址:http://www.cnblogs.com/argenbarbie/p/5410835.html

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