LeetCode - Interleaving String

本打算用类似于最长上升子序列的动态规划记忆化搜索实现,意外的竟然直接用回溯搜索就能pass Judge Large了,测试用例并不大是一个原因,还有就是子状态数可能要比想像中的要少。

public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        // Start typing your Java solution below
        // DO NOT write main() function
       if (s3.length() != s1.length() + s2.length())
            return false;
        else return dp(s1, s1.length()-1, s2, s2.length()-1, s3, s3.length()-1);
    }

    public boolean dp(String s1, int end1, String s2, int end2, String s3, int end3) {
        if (end3 < 0)
            return true;
        else if (end1 <0) {
            return s2.substring(0,end2+1).equals(s3.substring(0, end3+1));
        } else if (end2 < 0) {
            return s1.substring(0,end1+1).equals(s3.substring(0, end3+1));
        }
        char c3 = s3.charAt(end3);
        char c1 = s1.charAt(end1);
        char c2 = s2.charAt(end2);
        if (c3 == c1 && c3 == c2) {
            return dp(s1, end1-1, s2, end2, s3, end3-1) || dp(s1, end1, s2, end2-1, s3, end3-1);
        } else if (c3 == c1)
            return dp(s1, end1-1, s2, end2, s3, end3-1);
        else if (c3 == c2)
            return dp(s1, end1, s2, end2-1, s3, end3-1);
        else
            return false;
    }
}
运行结果:

Run Status:  Accepted!
Program Runtime:  640 milli secs
Progress:  99/ 99 test cases passed.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值