Interleaving String

本文介绍了一个使用动态规划解决字符串交叉匹配问题的算法。该算法通过递推关系式判断第三个字符串是否能由前两个字符串交叉组成,并给出了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.题目

给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。

比如 s1 = "aabcc" s2 = "dbbca"

    - 当 s3 = "aadbbcbcac",返回  true.

    - 当 s3 = "aadbbbaccc", 返回 false.

2.算法

这是动态规划的题目,递推关系式为res[i][j] = res[i-1][j]&&s1.charAt(i-1)==s3.charAt(i+j-1) || res[i][j-1]&&s2.charAt(j-1)==s3.charAt(i+j-1)

    public boolean isInterleave(String s1, String s2, String s3)
    {
        // write your code here
        if (s1.length() + s2.length() != s3.length())
        {
        	return false;
        }
        String minWord = s1.length()>s2.length()?s2:s1;  
        String maxWord = s1.length()>s2.length()?s1:s2;  
        boolean[] res = new boolean[minWord.length()+1];
        res[0] = true;
        for (int i = 0; i < minWord.length(); i++)
        {
        	res[i + 1] = res[i] && minWord.charAt(i) == s3.charAt(i);
        }
        for (int i = 0; i < maxWord.length(); i++)
        {
        	res[0] = res[0] && maxWord.charAt(i) == s3.charAt(i);
        	for (int j = 0; j < minWord.length(); j++)
        	{
        		res[j+1] = res[j+1]&&maxWord.charAt(i)==s3.charAt(i+j+1) || res[j]&&minWord.charAt(j)==s3.charAt(i+j+1); 
        	}
        }
        return res[minWord.length()];
    }

原帖连接http://blog.youkuaiyun.com/linhuanmars/article/details/24683159
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值