[Lintcode] Interleaving String 交叉字符串

本文介绍了一种判断字符串s3是否由s1和s2交错组成的高效算法,采用动态规划方法解决该问题,并提供了具体实现代码。

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

Given three strings: s1s2s3, determine whether s3 is formed by the interleaving of s1and s2.

Example

For s1 = "aabcc", s2 = "dbbca"

  • When s3 = "aadbbcbcac", return true.
  • When s3 = "aadbbbaccc", return false.
要求时间复杂度小于O(N×N)。分析:关于字符串比较的问题,可以考虑使用DP求解。这里可以使用二维DP。

res[i][j] 代表s1中前i个字符与s2中前j个字母是否可以交叉匹配成为s2中前i+j个字符。

公式为:

        if s3[i + j] = s1[i] = s2[j]. res[i][j] = res[i - 1][j] || res[i][j - 1]
        if s3[i + j] = s1[i] res[i][j] = res[i - 1][j] 
        if s3[i + j] = s2[j] res[i][j] = res[i][j - 1]
         else s3[i + j] = false;

初始条件是res[0][0] = true. 即s1前0个字符加s2前0个字符,可以拼凑成s3前0个字符。


public class Solution {
    /**
     * Determine whether s3 is formed by interleaving of s1 and s2.
     * @param s1, s2, s3: As description.
     * @return: true or false.
     */
    public boolean isInterleave(String s1, String s2, String s3) {

        if(s1.length() + s2.length() != s3.length()) return false;
        
        boolean[][] res = new boolean[s1.length() + 1][s2.length() + 1];
        res[0][0] = true;
        for(int i = 1; i <= s1.length(); i++) 
            res[i][0] = res[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1);
        for(int j = 1; j <= s2.length(); j++) 
            res[0][j] = res[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);
        for(int i = 1; i <= s1.length(); i++) {
            for(int j = 1; j <= s2.length(); j++) {
                if(s3.charAt(i + j - 1) == s1.charAt(i - 1) &&
                s3.charAt(i + j - 1) == s2.charAt(j - 1)) {
                    res[i][j] = res[i - 1][j] || res[i][j - 1];
                } else if (s3.charAt(i + j - 1) == s1.charAt(i - 1)) {
                    res[i][j] = res[i - 1][j];
                } else if (s3.charAt(i + j - 1) == s2.charAt(j - 1)) {
                    res[i][j] = res[i][j - 1];
                } else 
                    res[i][j] = false;
            }
        }
        
        return res[s1.length()][s2.length()];
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值