题目
给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
示例 1:
输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
输出: true
示例 2:
输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
输出: false
解题思路
dfs
dfs, compare s1[i]
and s3[p]
or s2[j]
and s3[p]
, then dfs. Use memo to speed up.
Time complexity:
o
(
l
e
n
(
s
1
)
∗
l
e
n
(
s
2
)
)
o(len(s1)*len(s2))
o(len(s1)∗len(s2))
Space complexity:
o
(
l
e
n
(
s
1
)
∗
l
e
n
(
s
2
)
)
o(len(s1)*len(s2))
o(len(s1)∗len(s2))
dp
dp版,用dp[i][j]
表示s1[:i], s2[:j]
能够匹配s3[:i + j]
的情况,则转移方程:
dp[i][j] = dp[i - 1][j] and s1[i] == s3[i + j] or dp[i][j - 1] and s2[j] == s3[i + j]
代码
dfs
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
memo = {}
def dfs(i1: int, i2: int, p: int) -> bool:
if p == len(s3) and i1 == len(s1) and i2 == len(s2):
return True
if (i1, i2, p) in memo:
return memo[(i1, i2, p)]
res = False
if i1 < len(s1) and p < len(s3) and s3[p] == s1[i1]:
res |= dfs(i1 + 1, i2, p + 1)
if i2 < len(s2) and p < len(s3) and s3[p] == s2[i2]:
res |= dfs(i1, i2 + 1, p + 1)
memo[(i1, i2, p)] = res
return memo[(i1, i2, p)]
return dfs(0, 0, 0)
dp
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
dp = [[True] * (len(s2) + 1) for _ in range(len(s1) + 1)]
# init
for col in range(1, len(s2) + 1):
dp[0][col] = dp[0][col - 1] and (s2[col - 1] == s3[col - 1])
for row in range(1, len(s1) + 1):
dp[row][0] = dp[row - 1][0] and (s1[row - 1] == s3[row - 1])
# dp
for row in range(1, len(s1) + 1):
for col in range(1, len(s2) + 1):
dp[row][col] = (dp[row - 1][col] and (s1[row - 1] == s3[row + col - 1])) or (dp[row][col - 1] and (s2[col - 1] == s3[row + col - 1]))
return dp[-1][-1]