算法学习

算法题--判断s3是否由s1和s2穿插而成

2020-04-27  本文已影响0人  岁月如歌2020
image.png

0. 链接

题目链接

1. 题目

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

2. 思路1: 动态规划

dp[0][0] = True
i = 1~m
dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1]

j = 1~n
dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1]

i = 0~m-1, j=0~n-1
dp[i + 1][j + 1] = (dp[i][j + 1] and s1[i] == s3[i + j + 1]) or (dp[i + 1][j] and s2[j] == s3[i + j + 1])

3. 代码

# coding:utf8


class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        m = len(s1)
        n = len(s2)
        if len(s3) != m + n:
            return False

        dp = [[False] * (n + 1) for _ in range(m + 1)]
        dp[0][0] = True

        for i in range(1, m + 1):
            dp[i][0] = dp[i - 1][0] and (s1[i - 1] == s3[i - 1])
        for j in range(1, n + 1):
            dp[0][j] = dp[0][j - 1] and (s2[j - 1] == s3[j - 1])
        for i in range(m):
            for j in range(n):
                dp[i + 1][j + 1] = (dp[i][j + 1] and s1[i] == s3[i + j + 1]) \
                                or (dp[i + 1][j] and s2[j] == s3[i + j + 1])
        return dp[m][n]


def my_test(solution, s1, s2, s3):
    print('input: s1={}, s2={}, s3={}; output: {}'.format(
        s1, s2, s3, solution.isInterleave(s1, s2, s3)))


solution = Solution()
my_test(solution, 'aabcc', 'dbbca', 'aadbbcbcac')
my_test(solution, 'aabcc', 'dbbca', 'aadbbbaccc')
my_test(solution, "db", "b", "cbb")


输出结果

input: s1=aabcc, s2=dbbca, s3=aadbbcbcac; output: True
input: s1=aabcc, s2=dbbca, s3=aadbbbaccc; output: False
input: s1=db, s2=b, s3=cbb; output: False

结果

image.png
上一篇 下一篇

猜你喜欢

热点阅读