【Leetcode】Interleaving String - 动态规划二维转一维

本文通过Java实现动态规划算法解决字符串交织问题,详细解释了递归式和具体实现步骤,包括初始化、循环和判断条件,展示了如何通过比较三个字符串s1、s2和s3来判断s3是否由s1和s2交织而成。

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.

Java:

http://blog.youkuaiyun.com/linhuanmars/article/details/24683159

动态规划

递归式:

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 class Solution {  
    public boolean isInterleave(String s1, String s2, String s3) {  
       // Note: The Solution object is instantiated only once and is reused by each test case.  
        if (s1 == null || s2 == null || s3 == null) return false;  
        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()]; 
        
    }  
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值