LeetCode 题解(35): Interleaving String

题目:

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.

题解:

动态规划经典题目。用一个(s1.length()+1) x (s2.length()+1)维的二维bool矩阵表示任意位置(i,j)处的子串s1(1~j-1),s2(1~i-1)是否可以组成s3(1 ~ i+j-1)

       a   a   b   c   c

      T   T   F   F   F

d F F   T 

b F      T

b F      T

c F      T   T   T

a T                T   T


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

你可能感兴趣的:(Algorithm,LeetCode,String,Interleaving)