Monday, December 15, 2014

Interleaving String

Q:
Given s1, s2, s3, 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.

T:
Let m=s1.size()-1, n=s2.size()-1. If s3[m+n+1] == s1[m], then the problem is equivalent to examine whether s1.substr(0, m), s2 can interleave to make s3. So we can solve this by DP. let match[i][j] be whether s1.substr(0, i) and s2.substr(0, j) can interleave to make s3.substr(0, i+j). We have:
match[i][j] = match[i-1][j], if s1[i-1] == s3[i+j-1]
                  or match[i][j-1], if s2[j-1] == s3[i+j-1]
                  or false.
match[0][0] = true.
match[0][j] =  match[0][j-1], if s2[j-1] == s3[j-1]
                  or false.


A:


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

No comments:

Post a Comment