【LeetCode】97. 交错字符串 结题报告 (C++)

原题地址:https://leetcode-cn.com/problems/interleaving-string/description/

题目描述:

给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。

示例 1:

输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出: true
示例 2:

输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出: false

 

解题方案:

又是dp的题目,好难啊。。。参考链接:https://blog.csdn.net/xygy8860/article/details/47102283

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int len1 = s1.length();
    	int len2 = s2.length();
    	int len3 = s3.length();
    	
    	if(len1 + len2 != len3)
    		return false;
    	
    	bool f[len1 + 1][len2 + 1];
    	f[0][0] = true;//第一个设置为true
    	for(int i = 0; i < len1 + 1; i++){
    		for(int j = 0; j < len2 + 1; j++){
    			//i>0,j>0的条件是摒除i=0j=0的值
    			if(j > 0){
    				f[i][j] = f[i][j - 1] && (s3[i + j - 1] == s2[j - 1]);
    			}
    			if(i > 0){
    				f[i][j] = f[i][j] || ( f[i - 1][j] && (s3[i + j - 1] == s1[i - 1]));
    			}
    		}
    	}
    	return f[len1][len2];
    }
};

 

你可能感兴趣的:(【LeetCode】97. 交错字符串 结题报告 (C++))