LeetCode 97. 交错字符串(动态规划)

题目描述

给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
示例 1:
输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac”
输出: true
示例 2:
输入: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbbaccc”
输出: false

思路

详见链接

代码

class Solution:
	def isInterleave(self,s1:str,s2:str,s3:str)->bool:
		n1 = len(s1)
		n2 = len(s2)
		n3 = len(s3)
		if n1 + n2 != n3:
			return 0
		dp = [[False]*(n2+1) for _ in range(n1+1)]
		dp[0][0] = True
		for i in range(1,n1+1):
			dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]
		for j in range(1,n2+1):
			dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]
		for i in range(1,n1+1):
			for j in range(1,n2+1):
				dp[i][j] = (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])
		return dp[-1][-1]
test = Solution()
test.isInterleave("aabcc","dbbca","aadbbcbcac")

效果

LeetCode 97. 交错字符串(动态规划)_第1张图片

你可能感兴趣的:(Leetcode)