算法:交错字符串【动态规划】

交错字符串

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

示例 1:

输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac”
输出: true
示例 2:

输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc”
输出: false
LeetCode

分析

算法:交错字符串【动态规划】_第1张图片
另外,可进行空间压缩,把二维dp数组压缩为一维。

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False
        # 初始化dp数组
        dp = [[False] * (len(s2)+1) for _ in range(len(s1)+1)]
        dp[0][0] = True
        for i in range(1, len(s2)+1):
            if s2[:i] == s3[:i]:
                dp[0][i] = True
        for i in range(1, len(s1)+1):
            if s1[:i] == s3[:i]:
                dp[i][0] = True
        
        for i in range(1, len(s1)+1):
            for j in range(1, len(s2)+1):   # 两种情况满足一种即为True
                if (dp[i-1][j] is True and s1[i-1] == s3[i+j-1]) or (dp[i][j-1] is True and s2[j-1] == s3[i+j-1]):
                    dp[i][j] = True
        
        return dp[-1][-1]

你可能感兴趣的:(算法)