97. Interleaving String

97. Interleaving String

class Solution:
    def dfs(self,i,j,k):
        if self.ans==True:return 
        if self.dp[i][j]!=-1:return 0
        self.dp[i][j]=1
        if k==len(self.s3):
            self.ans=True
        # print(i,j,k)
        if i+1<=len(self.s1):
            if self.s1[i]==self.s3[k]:
                self.dfs(i+1,j,k+1)
            else:
                self.dp[i+1][j]=0
        if j+1<=len(self.s2):
            if self.s2[j]==self.s3[k]:
                self.dfs(i,j+1,k+1)
            else:
                self.dp[i][j+1]=0
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        # print("------------")
        if len(s1)==0:return s2==s3
        if len(s2)==0:return s1==s3
        if len(s1)+len(s2)!=len(s3):return False
        self.ans=False
        self.dp =[[-1 for j in range(len(s2)+1)] for i in range(len(s1)+1)]
        self.s1,self.s2,self.s3=s1,s2,s3
        self.dfs(0,0,0)
        return self.ans
        # return self.dp[len(s1)][len(s2)]==1
        

你可能感兴趣的:(leetcode)