leetcode 每日一题 97. 交错字符串

动态规划

思路:

用dp[i][j]表示s1前 i 个字符和s2前j个字符,能否匹配s3前i+j个字符。

dp[0][0] = True

当i=0时,只需要看s2的前j个字符是否依次和s3的前j个字符匹配,即dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]

当j=0时,只需要看s1的前i个字符是否依次和s3的前i个字符匹配,即dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]

当i != 0 且 j != 0 ,则如果s1[i-1] == s3[i+j-1] 并且 dp[i-1][j] 为True 或者 s2[j-1] == s3[i+j-1] 并且dp[i][j-1]为True 时,dp[i][j]为True,

dp[i][j]=(dp[i][j-1] and s2[j-1]==s3[i+j-1]) or (dp[i-1][j] and s1[i-1]==s3[i+j-1])

代码:

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        len1=len(s1)
        len2=len(s2)
        len3=len(s3)
        if(len1+len2!=len3):
            return False
        dp=[[False]*(len2+1) for i in range(len1+1)]
        dp[0][0]=True
        for i in range(1,len1+1):
            dp[i][0]=(dp[i-1][0] and s1[i-1]==s3[i-1])
        for i in range(1,len2+1):
            dp[0][i]=(dp[0][i-1] and s2[i-1]==s3[i-1])
        for i in range(1,len1+1):
            for j in range(1,len2+1):
                dp[i][j]=(dp[i][j-1] and s2[j-1]==s3[i+j-1]) or (dp[i-1][j] and s1[i-1]==s3[i+j-1])
        return dp[-1][-1]

 

posted @ 2020-06-22 14:31  nil_f  阅读(210)  评论(0编辑  收藏  举报