97. Interleaving String
暴力递归
class Solution:
def isInterleave(self
, s1
: str, s2
: str, s3
: str) -> bool:
size1
, size2
, size3
= len(s1
), len(s2
), len(s3
)
if size1
+ size2
!= size3
:
return False
def ishelp(index1
, index2
, index3
):
if index1
== size1
:
return s2
[index2
:] == s3
[index3
:]
if index2
== size2
:
return s1
[index1
:] == s3
[index3
:]
if (s3
[index3
] == s1
[index1
] and ishelp
(index1
+1, index2
, index3
+1)):
return True
if (s3
[index3
] == s2
[index2
] and ishelp
(index1
, index2
+1, index3
+1)):
return True
return False
return ishelp
(0, 0, 0)
带备忘录的递归
class Solution:
def isInterleave(self
, s1
: str, s2
: str, s3
: str) -> bool:
size1
, size2
, size3
= len(s1
), len(s2
), len(s3
)
if size1
+ size2
!= size3
:
return False
memo
= [[-1]*(size2
+1) for _
in range(size1
+1)]
def ishelp(index1
, index2
, index3
):
if memo
[index1
][index2
] != -1:
return memo
[index1
][index2
] == 1
if index1
== size1
:
return s2
[index2
:] == s3
[index3
:]
if index2
== size2
:
return s1
[index1
:] == s3
[index3
:]
if (s3
[index3
] == s1
[index1
] and ishelp
(index1
+1, index2
, index3
+1)) \
or (s3
[index3
] == s2
[index2
] and ishelp
(index1
, index2
+1, index3
+1)):
memo
[index1
][index2
] = 1
return True
memo
[index1
][index2
] = 0
return False
return ishelp
(0, 0, 0)
动态规划
class Solution:
def isInterleave(self
, s1
: str, s2
: str, s3
: str) -> bool:
size1
, size2
, size3
= len(s1
), len(s2
), len(s3
)
if size1
+ size2
!= size3
:
return False
dp
= [[False]*(size2
+1) for _
in range(size1
+1)]
for i
in range(size1
+1):
for j
in range(size2
+1):
if i
== 0 and j
== 0:
dp
[i
][j
] = True
elif i
== 0:
dp
[i
][j
] = s2
[j
- 1] == s3
[i
+ j
- 1] and dp
[i
][j
- 1]
elif j
== 0:
dp
[i
][j
] = s1
[i
- 1] == s3
[i
+ j
- 1] and dp
[i
- 1][j
]
else:
dp
[i
][j
] = (s1
[i
- 1] == s3
[i
+j
-1] and dp
[i
-1][j
]) or (s2
[j
- 1] == s3
[i
+j
-1] and dp
[i
][j
-1])
return dp
[size1
][size2
]
转载请注明原文地址: https://lol.8miu.com/read-29519.html