97. 交错字符串

递归,DP两种方法

 

 

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

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        # if sorted(s1+s2)!=sorted(s3):
        #     return False
        # l1,l2,l3 = len(s1),len(s2),len(s3)
        # # if l1==l2==l3==0:return True
        # dp = [[False]*(l2+1) for _ in range(l1+1)]
        # dp[0][0] = True
        # i=j=-1
        # while i<l1-1:
        #     i+=1
        #     if s1[i]==s3[i]:dp[i+1][0]=True
        #     else: break
        # while j<l2-1:
        #     j+=1
        #     if s2[j] == s3[j]:dp[0][j+1]=True
        #     else:break

        # for i in range(1,l1+1):
        #     for j in range(1,l2+1):
        #         # 比如 s1第三个数 s2第二个数 i=3 j=2; s1[2] == s3[3+2-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])
        # for i in dp:
        #     print(i)
        # return dp[-1][-1]

        l1,l2,l3 = len(s1),len(s2),len(s3)
        p1=p2=p3=0
        while p1<l1 and p2<l2 and p3<l3:
            if s1[p1]==s2[p2]==s3[p3]:
                res1 = self.isInterleave(s1[p1+1:], s2[p2:], s3[p3+1:]) 
                res2 = self.isInterleave(s1[p1:], s2[p2+1:], s3[p3+1:])
                res = res1 or res2
                return res
            elif s1[p1] == s3[p3]:
                p1+=1
                p3+=1
            elif s2[p2] == s3[p3]:
                p2+=1
                p3+=1
            else:
                return False
        if p1==l1:
            return s2[p2:] == s3[p3:]
        elif p2 == l2:
            return s1[p1:] == s3[p3:]

  

posted @ 2020-12-16 14:13  ChevisZhang  阅读(85)  评论(0编辑  收藏  举报