-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL139.py
More file actions
46 lines (33 loc) · 1.36 KB
/
Copy pathL139.py
File metadata and controls
46 lines (33 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 139. 单词拆分
from typing import List
class Solution:
def dfs(self, index, s, wordDict, dp):
if index == len(s): return True
if dp[index] != -1: return True if dp[index] == 1 else False
ans = False
for i in range(index, len(s)):
if s[index:i + 1] in wordDict:
ans = ans or self.dfs(i + 1, s, wordDict, dp)
dp[index] = 1 if ans else 0
return ans
def wordBreak1(self, s: str, wordDict: List[str]) -> bool:
dp = [-1] * (len(s))
return self.dfs(0, s, wordDict, dp)
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for j in range(0, i):
if dp[j] and s[j:i] in wordDict:
dp[i] = True
break
return dp[n]
if __name__ == '__main__':
s = Solution()
ans = s.wordBreak("applepenapple", ["cats", "dog", "sand", "and", "cat"])
print(ans)
print(s.wordBreak("leetcode", ["leet", "code"]))
print(s.wordBreak(
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab",
["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa", "aaaaaaa", "aaaaaaaa", "aaaaaaaaa", "aaaaaaaaaa"]))