[Leetcode]@python 97. Interleaving String

本文针对LeetCode上的一道经典题目——交错字符串问题进行解析。通过动态规划的方法来判断一个字符串是否能由另外两个字符串交错组成。文章详细介绍了解题思路,并提供了一段Python实现的代码。

题目链接

https://leetcode.com/problems/interleaving-string/

题目原文

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.

题目大意

给定字符串s1, s2, s3,判断s3是否由s1和s2交叉组成的

解题思路

动态规划:dp[i][j]表示s1[0...i-1]和s2[0...j-1]是否可以拼接为s3[0...i+j-1],可以拼接为true,不可以拼接为false

代码

class Solution(object):
    def isInterleave(self, s1, s2, s3):
        """
        :type s1: str
        :type s2: str
        :type s3: str
        :rtype: bool
        """
        if len(s1) + len(s2) != len(s3):
            return False
        dp = [[False for i in range(len(s2) + 1)] for j in range(len(s1) + 1)]
        dp[0][0] = True

        for i in range(1, len(s1) + 1):
            if dp[i - 1][0] and s3[i - 1] == s1[i - 1]:
                dp[i][0] = True
        for i in range(1, len(s2) + 1):
            if dp[0][i - 1] and s3[i - 1] == s2[i - 1]:
                dp[0][i] = True

        for i in range(1, len(s1) + 1):
            for j in range(1, len(s2) + 1):
                if (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]):
                    dp[i][j] = True
        return dp[len(s1)][len(s2)]

转载于:https://www.cnblogs.com/slurm/p/5221580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值