[97][困难][动态规划][DFS][BFS] 交错字符串
题目描述
输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出: true输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出: false解题思路
动态规划
DFS + 记忆化
BFS + 记忆化
参考资料
最后更新于
输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出: true输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出: false最后更新于
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n, m, l = len(s1), len(s2), len(s3)
if n + m != l:
return False
dp = [[False] * (m + 1) for _ in range(n + 1)]
# 初始化状态矩阵的初始条件, 即边际状态
dp[0][0] = True
for i in range(n):
if s1[i] == s3[i]:
dp[i + 1][0] = True
else:
break
for i in range(m):
if s2[i] == s3[i]:
dp[0][i + 1] = True
else:
break
for i in range(n):
for j in range(m):
if (s3[i + j + 1] == s1[i] and dp[i][j + 1]) or (s3[i + j + 1] == s2[j] and dp[i + 1][j]):
dp[i + 1][j + 1] = True
return dp[-1][-1]class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n, m, l = len(s1), len(s2), len(s3)
if n + m != l:
return False
seen = dict()
def dfs(i, j):
if (i, j) in seen:
return seen[(i, j)]
res = (i < n and s1[i] == s3[i + j] and dfs(i + 1, j)) or (j < m and s2[j] == s3[i + j] and dfs(i, j + 1)) or (i + j == l)
seen[(i, j)] = res
return res
return dfs(0, 0)class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n, m, l = len(s1), len(s2), len(s3)
if n + m != l:
return False
seen = set()
stack = [(0, 0)]
while stack:
indices = stack.pop()
if indices in seen:
continue
seen.add(indices)
i, j = indices
if i == n and j == m:
return True
if 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))
return False