[Leetcode] 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交叉组合而成。

分析:

  dp[i][j]表示当s1在第i个位置,s2在第j个位置,s3在第i+j位置时,s3是否是s1和s2的交叉组合,dp[i][j]值为true或者false。第0个位置表示空字符串。

  当s1和s2都为空,s3也为空时,那么应该返回true;

  当s1为空时,如果s2当前位置j前面的子字符与s3当前位置前面的字符串相等时,即dp[0][j-1]=true时,若s2当前位置与s3当前位置的字符相等,则当前位置符合条件,即dp[0][j]=true,否则dp[0][j]=false;s2为空时,同理。

  若s1和s2都不为空时,当s1在i位置,s2在j位置时,如果我们是从i-1,j位置到底当前位置i,j时,若d[i-1][j]=true,并且s1[i]==s3[i+j]时,则dp[i][j]=true;

参考:https://discuss.leetcode.com/topic/3532/my-dp-solution-in-c/2

DP table represents if s3 is interleaving at (i+j)th position when s1 is at ith position, and s2 is at jth position. 0th position means empty string.

So if both s1 and s2 is currently empty, s3 is empty too, and it is considered interleaving. If only s1 is empty, then if previous s2 position is interleaving and current s2 position char is equal to s3 current position char, it is considered interleaving. similar idea applies to when s2 is empty. when both s1 and s2 is not empty, then if we arrive i, j from i-1, j, then if i-1,j is already interleaving and i and current s3 position equal, it s interleaving. If we arrive i,j from i, j-1, then if i, j-1 is already interleaving and j and current s3 position equal. it is interleaving.

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int n1=s1.size();
        int n2=s2.size();
        int n3=s3.size();
        
        if(n1+n2!=n3) return false;
        
        vector<vector<int>> dp(n1+1, vector<int>(n2+1, false));
        
        for(int i=0;i<n1+1;i++)
            for(int j=0;j<n2+1;j++)
            {
                if(i==0 && j==0)//s1和s2都为空字符串的情况
                {
                    dp[i][j] = true;
                }
                else if(i==0)//s1为空字符串的情况
                {
                    dp[i][j]=dp[i][j-1]&&(s2[j-1]==s3[i+j-1]);
                }
                else if(j==0)//s2为空字符串的情况
                {
                    dp[i][j]=dp[i-1][j]&&(s1[i-1]==s3[i+j-1]);                  
                }
                else//s1和s2都不为空字符串的情况
                {
                    dp[i][j]=(dp[i][j-1]&&(s2[j-1]==s3[i+j-1]))||(dp[i-1][j]&&(s1[i-1]==s3[i+j-1]));
                }
            }
        return dp[n1][n2];
        
    }
};
原文地址:https://www.cnblogs.com/hejunlin1992/p/7599674.html