LeetCode: Interleaving String

来源:互联网 发布:ae cc 2014 mac 破解 编辑:程序博客网 时间:2024/05/01 06:37

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.

DP问题。

mach(s1, l1, s2, l2, s3, l3) = (s1[last]==s3[last])&&match(s1, l1-1, s2, l2, s3, l3-1) ||  (s2[last]==s3[last])&&match(s1, l1, s2, l2-1, s3, l3-1)。

class Solution {public:    bool isInterleave(string s1, string s2, string s3) {        // Start typing your C/C++ solution below        // DO NOT write int main() function            int len1 = s1.size();        int len2 = s2.size();        int len3 = s3.size();        if (len3 != len1 + len2)            return false;                vector< vector<bool> > match(len2+1, vector<bool>(len1+1, false));        match[0][0] = true;        for (int i = 1; i <= len1; ++i)        {            if (s1[i-1] == s3[i-1])                match[0][i] = true;            else                break;        }        for (int j = 1; j <= len2; ++j)        {            if (s2[j-1] == s3[j-1])                match[j][0] = true;            else                break;        }                for (int j = 1; j <= len2; ++j)        {            for (int i = 1; i <= len1; ++i)            {                if (s1[i-1] == s3[i+j-1])                    match[j][i] = match[j][i-1] || match[j][i];                                    if (s2[j-1] == s3[i+j-1])                    match[j][i] = match[j-1][i] || match[j][i];            }        }        return match[len2][len1];    }};

原创粉丝点击