Leetcode 97. 交错字符串 (动态规划高频面试题)

Leetcode 97. 交错字符串 (动态规划高频面试题)_第1张图片

 

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        // dp[i][j] 表示s1的前i个字母和s2的前j个字母,是否能交错成s3的前i+j个字母
        int n = s1.size(), m = s2.size();
        if(n+m!=s3.size()) return false;
        s1 = " "+s1, s2 = " "+s2, s3 = " "+s3;
        vector> dp(n+1,vector(m+1,false));
        for(int i=0;i<=n;i++){
            for(int j=0;j<=m;j++){
                if(i==0&&j==0) dp[i][j] = true;
                if(i>0&&s1[i]==s3[i+j]) dp[i][j] = dp[i-1][j];
                if(j>0&&s2[j]==s3[i+j]) dp[i][j] = dp[i][j] || dp[i][j-1];
            }
        }
        return dp[n][m];
    }
};

 

你可能感兴趣的:(算法)