Hard-题目33:97. 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,s2,s3,判断s3是不是s1和s2交错组合而成。
题目分析:
很明显这个问题可以缩减为下面的子问题:s1的前i个字符与s2的前j个字符能否交错构成s3的前i+j个字符。那么就用DP来做。
设dp(i,j)表示s1的前i个字符与s2的前j个字符能否交错构成s3的前i+j个字符。那么转移关系如下:

dp(I,j)=(dp(i-1,j)&&s1[i-1]==s3[i+j-1])||(dp(I,j-1)&&s2[j-1]==s3[i+j-1])

很好理解,如果dp(i-1,j)==true,则只需要看s3的第i+j个字符和s1的第i个字符是否一样,dp(I,j-1)==true的情况也同理。时间复杂度仅为O(s1.length*s2.length).
源码:(language:cpp)

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

成绩:
12ms,8.48%,8ms,28.70%

你可能感兴趣的:(Hard-题目33:97. Interleaving String)