交叉字符串的判定算法

交叉字符串的判定

1.问题描述

Given s1, s2, s3, 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.

2.原始思路

运用递归算法,判断s1或s2当前字母与s3当前字母是否匹配,此时可分为三种情况:

  1. 若仅s1与s3当前字母匹配则将s1与s3的当前字母删去形成s1’与s3’从而形成新的子问题(s1’, s2, s3’);
  2. 若仅s2与s3当前字母匹配则将s2与s3的当前字母删去形成s1’与s3’从而形成新的子问题(s1, s2’, s3’);
  3. 若s1和s2当前字母均与s3当前字母匹配则分别解(s1’, s2, s3’)和(s1, s2’, s3’),并返回它们的或。
    代码如下:
def isInterleave(s1, s2, s3):
    """
    :type s1: str
    :type s2: str
    :type s3: str
    :rtype: bool
    """
    if not len(s3) == len(s1) + len(s2):
            return False
    if len(s1) != 0 and len(s2) != 0 and s1[0] == s2[0] and s1[0] == s3[0]:
        if isInterleave(s1[1:], s2, s3[1:]):
            return True
        else: 
            return isInterleave(s1, s2[1:], s3[1:])
    if len(s1) == 0:
        return cmp(s2, s3) == 0;
    elif s1[0] == s3[0]:
        return isInterleave(s1[1:], s2, s3[1:])
    if len(s2) == 0:
        return cmp(s2, s3) == 0
    elif s2[0] == s3[0]:
        return isInterleave(s1, s2[1:], s3[1:])

此方法思路简单,实现容易,但是效率低下,对同一个子问题会出现重复计算的情况。这里我们可以通过动态规划表更高效的解决这个问题。

2.动态规划算法

python代码如下:

def isInterleave(s1, s2, s3):
    """
    :type s1: str
    :type s2: str
    :type s3: str
    :rtype: bool
    """
    if not len(s3) == len(s1) + len(s2):
        return False
    table = [[False for i in range(len(s2) + 1)] for i in range(len(s1) + 1)]
    for i in range(len(s1) + 1):
        for j in range(len(s2) + 1):
            if i == 0 and j == 0:
                table[i][j] = True
            elif i == 0:
                table[i][j] = (table[i][j - 1] and s2[j - 1] == s3[i + j - 1])
            elif j == 0:
                table[i][j] = (table[i - 1][j] and s1[i - 1] == s3[i + j - 1])
            else:
                table[i][j] = (table[i][j - 1] and s2[j - 1] == s3[i + j - 1]) or (table[i - 1][j] and s1[i - 1] == s3[i + j - 1])
    return table[-1][-1]

具体参考LeetCode上的解法:

https://discuss.leetcode.com/topic/3532/my-dp-solution-in-c

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值