Sunday, March 15, 2015

97 Interleaving String

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.
Solution 1: 2 dimensional matrix:
class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        if (s3.size()>s1.size()+s2.size())
            return false;
        int m = s1.size();
        int n = s2.size();
        vector<vector<bool>> matrix = vector<vector<bool>>(m+1, vector<bool>(n+1,false));
        
        matrix[0][0]=true;
        for (int i=1;i<=m;i++)
        {
            if (s3[i-1]==s1[i-1] && matrix[i-1][0])
                matrix[i][0]=true;
        }
        for (int j=1;j<=n;j++)
        {
            if (s3[j-1]==s2[j-1] && matrix[0][j-1])
                matrix[0][j]=true;
        }
        for (int i=1;i<=m;i++)
        {
            for (int j=1;j<=n;j++)
            {
                if (matrix[i-1][j] && s3[i+j-1]==s1[i-1] || matrix[i][j-1] && s3[i+j-1]==s2[j-1])
                    matrix[i][j]=true;
            }
        }
        return matrix[m][n];
    }
};
Solution 2: 1 dimensional vector
class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        if (s3.size()>s1.size()+s2.size())
            return false;
        int m = s1.size();
        int n = s2.size();
        vector<bool> res = vector<bool>(n+1,false);
        
        res[0]=true;
        for (int j=1;j<=n;j++)
        {
            res[j]=s3[j-1]==s2[j-1] && res[j-1];
        }
        for (int i=1;i<=m;i++)
        {
            res[0]=s1[i-1]==s3[i-1] && res[0];
            for (int j=1;j<=n;j++)
            {
                res[j]=res[j] && s3[i+j-1]==s1[i-1] || res[j-1] && s3[i+j-1]==s2[j-1];
            }
        }
        return res[n];
    }
};

No comments:

Post a Comment