Leetcode97. Interleaving String

题目:Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

题目分析:给定两个字符串s1,s2,判断字符串s3是否能由s1,s2的交叉链接组成。

很显然,这种字符串匹配的题容易想到递归,但一定会超时……所以考虑用动态规划的方法。

思路:动态规划要利用数组。使用一个二维数组judge[][],其中judge[i][j]表示字符串 s1 前 i 项, s2 前 j 项已与 s3 前i+j 项匹配。

每计算一项judge[i][j],要看其左边一项,即judge[i][j-1]是否为true及s2的第j项是否与s3匹配;或者其上边一项,即judge[i-1][j-1]是否为true及s1的第i项是否与s3匹配;

举例:s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"

s1\s2 dbbca
 true     
atrue     
atruetruetruetruetrue 
b truetrue true 
c  truetruetruetrue
c   true true

代码: 

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 **judge;
    judge=new bool*[len1+1];
    for(int i=0;i<len1+1;i++){
        judge[i]=(bool *)calloc(sizeof(bool),(len2+1));
    }
    for(int i=0;i<=len1;i++){
	for(int j=0;j<=len2;j++){
	    if(i==0&&j==0)
                judge[i][j]= true;
	    else if(i==0)
		judge[i][j]= s2[j-1]==s3[j-1] && judge[i][j-1];
	    else if(j==0)
                judge[i][j]= s1[i-1]==s3[i-1] && judge[i-1][j];
	    else 
		judge[i][j]= (s1[i-1]==s3[i+j-1] && judge[i-1][j])||( s2[j-1]==s3[i+j-1] && judge[i][j-1]);
	}
    }
    return judge[len1][len2];
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值