leetcode: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.

题目地址: https://oj.leetcode.com/problems/interleaving-string/

这道题参考网上的答案写了解答,但是实际上还不是很懂。。估计多不久就又得忘了,不过还是把解法记录一下把。。

代码:

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int l1=s1.length(),l2=s2.length(),l3=s3.length();
        if(l1==0&&l2==0&&l3==0) return true;
        
        if(l1==0){
            if(s3==s2) return true;
            else return false;
        }
        if(l2==0){ 
            if(s3==s1) return true;
            else return false;
        }
        if(l3!=l1+l2) return false;
        
        //ans[i][j]表示s1的前i个字符和s2的前j个字符能否交替组成s3的前i+j个字符
        vector<vector<bool> > ans(l1+1,vector<bool>(l2+1,false));
        
        int i=0,j=0;
		ans[0][0]=true;
        for(;i<l1;i++){
			if(s1[i]==s3[i]&&ans[i][0]) ans[i+1][0]=true;
		}
        for(;j<l2;j++){
			if(s2[j]==s3[j]&&ans[0][j]) ans[0][j+1]=true;
		}

		for(i=1;i<=l1;i++){
			for(j=1;j<=l2;j++){
				if(s1[i-1]==s3[i+j-1]&&ans[i-1][j]) ans[i][j]=true;
				if(s2[j-1]==s3[i+j-1]&&ans[i][j-1]) ans[i][j]=true;
			}
		}
        return ans[l1][l2];
        
        
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值