[Leetcode] Interleaving String

1986 단어
//Recursion  
class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        if (s1.size() + s2.size() == s3.size())
            return run(s1, s2, s3, 0, 0, 0);
            
        return false;
    }
    
    bool run(string s1, string s2, string s3, int idx1, int idx2, int idx3)
    {
        if (idx1 == s1.size() && idx2 == s2.size() && idx3 == s3.size())
            return true;
            
        bool res = false;
        if (idx1 < s1.size() && s1[idx1] == s3[idx3])
            res = res || run(s1, s2, s3, idx1 + 1, idx2, idx3 + 1);
            
        if (idx2 < s2.size() && s2[idx2] == s3[idx3])
            res = res || run(s1, s2, s3, idx1, idx2 + 1, idx3 + 1);
            
        return res;
    }
};
//DP
class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function    
        if (s1.size() + s2.size() != s3.size())                    
            return false;
            
        vector<vector<bool> > mat(s1.size() + 1, vector<bool>(s2.size() + 1));
        
        mat[0][0] = true;
        
        for (int i = 1; i <= s1.size(); ++i)
            mat[i][0] = mat[i - 1][0] && (s3[i - 1] == s1[i - 1]);
                
        for (int i = 1; i <= s2.size(); ++i)
            mat[0][i] = mat[0][i - 1] && (s3[i - 1] == s2[i - 1]);
        
        for (int i = 1; i <= s1.size(); ++i)
            for (int j = 1; j <= s2.size(); ++j)
                mat[i][j] = (mat[i][j - 1] && s2[j - 1] == s3[i + j - 1]) || (mat[i - 1][j] && s1[i - 1] == s3[i + j - 1]);
                
        return mat[s1.size()][s2.size()];        
    }    
};

좋은 웹페이지 즐겨찾기