classSolution:defisInterleave(self,s1:str,s2:str,s3:str) ->bool: n, m, l =len(s1),len(s2),len(s3)if n + m != l:returnFalse seen =dict()defdfs(i,j):if (i, j) in seen:return seen[(i, j)] res = (i < n and s1[i]== s3[i + j]anddfs(i +1, j)) or (j < m and s2[j]== s3[i + j]anddfs(i, j +1)) or (i + j == l) seen[(i, j)]= resreturn resreturndfs(0, 0)
BFS + 记忆化
其实此题中BFS与DFS思路很接近, 只是一个用递归, 一个用栈, 利用栈的特性.
classSolution:defisInterleave(self,s1:str,s2:str,s3:str) ->bool: n, m, l =len(s1),len(s2),len(s3)if n + m != l:returnFalse seen =set() stack = [(0,0)]while stack: indices = stack.pop()if indices in seen:continue seen.add(indices) i, j = indicesif i == n and j == m:returnTrueif i < n and s1[i]== s3[i + j]: stack.append((i +1, j))if j < m and s2[j]== s3[i + j]: stack.append((i, j +1))returnFalse