leetcode-97. 交错字符串

题目

给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。

示例 1:

输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出: true

示例 2:

输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出: false

解题思路

dfs

dfs, compare s1[i] and s3[p] or s2[j] and s3[p], then dfs. Use memo to speed up.

Time complexity: o ( l e n ( s 1 ) ∗ l e n ( s 2 ) ) o(len(s1)*len(s2)) o(len(s1)len(s2))
Space complexity: o ( l e n ( s 1 ) ∗ l e n ( s 2 ) ) o(len(s1)*len(s2)) o(len(s1)len(s2))

dp

dp版,用dp[i][j]表示s1[:i], s2[:j]能够匹配s3[:i + j]的情况,则转移方程:
dp[i][j] = dp[i - 1][j] and s1[i] == s3[i + j] or dp[i][j - 1] and s2[j] == s3[i + j]

代码

dfs

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        memo = {}
        def dfs(i1: int, i2: int, p: int) -> bool:
            if p == len(s3) and i1 == len(s1) and i2 == len(s2):
                return True
            if (i1, i2, p) in memo:
                return memo[(i1, i2, p)]
            res = False
            if i1 < len(s1) and p < len(s3) and s3[p] == s1[i1]:
                res |= dfs(i1 + 1, i2, p + 1)
            if i2 < len(s2) and p < len(s3) and s3[p] == s2[i2]:
                res |= dfs(i1, i2 + 1, p + 1)
            memo[(i1, i2, p)] = res
            return memo[(i1, i2, p)]
        return dfs(0, 0, 0)

dp

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False
        dp = [[True] * (len(s2) + 1) for _ in range(len(s1) + 1)]
        # init
        for col in range(1, len(s2) + 1):
            dp[0][col] = dp[0][col - 1] and (s2[col - 1] == s3[col - 1])
        for row in range(1, len(s1) + 1):
            dp[row][0] = dp[row - 1][0] and (s1[row - 1] == s3[row - 1])
        # dp
        for row in range(1, len(s1) + 1):
            for col in range(1, len(s2) + 1):
                dp[row][col] = (dp[row - 1][col] and (s1[row - 1] == s3[row + col - 1])) or (dp[row][col - 1] and (s2[col - 1] == s3[row + col - 1]))
        return dp[-1][-1]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值