用DFS算法可以解决,其中visited为了防止重复的遍历导致超时
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
que = [(0,0)]
visited = set((0,0))
while que:
m,n = que.pop()
if m+n == len3:
return True
if m<len1 and s1[m] == s3[m+n] and (m+1,n) not in visited:
que.append((m+1,n))
visited.add((m+1,n))
if n<len2 and s2[n] == s3[m+n] and (m,n+1) not in visited:
que.append((m,n+1))
visited.add((m,n+1))
return False