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.

这道题最初想用贪心,实际策略就错了

后面看了dp的做法。

就是根据当前状态,i表示查看S1的位置,j表示查看S2的位置,i+j表示到S3的位置。

需要判断如果当前状态可由两个串的前部分组成,再加入一个字符时候可以依然由两个字符串的前部分组成。

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int l1 =s1.size(),l2=s2.size(),l3=s3.size();
        if(l1+l2 != l3)return 0;
        vector<vector<bool> > dp;
        for(int i = 0 ; i < l2+1 ;i++)
        {
            vector<bool> bo(l1+1,0);
            dp.push_back(bo);
        }
        dp[0][0] = 1;
        for(int i = 0 ; i <l2+1 ;i++)
        {
            for(int j = 0 ; j < l1+1 ;j++)
            {
                if(dp[i][j] && i+j < l3)
                {
                    if(j<l1 && s3[i+j] == s1[j]) dp[i][j+1] = 1;
                    
                    if(i<l2 && s3[i+j] == s2[i]) dp[i+1][j] = 1;
                }
            }
        }
        
        return dp[l2][l1];

    }
    
};

  

原文地址:https://www.cnblogs.com/pengyu2003/p/3674786.html