-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path139_Word_Break.py
More file actions
34 lines (28 loc) · 982 Bytes
/
139_Word_Break.py
File metadata and controls
34 lines (28 loc) · 982 Bytes
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
"""
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
"""
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
if len(wordDict) == 0:
return False
def dfs(s, memo, wordDict):
if s in memo:
return memo[s]
if s in wordDict:
memo[s] = True
return True
# 1st way
for i in range(1, len(s)):
prefix = s[:i]
if prefix in wordDict and dfs(s[i:], memo, wordDict): # right in dict, check left string
memo[s] = True
return True
# 2nd way
for word in wordDict:
if s.startswith(word) and dfs(s[len(word):], memo, wordDict):
memo[s] = True
return True
memo[s] = False
return False
return dfs(s, {}, set(wordDict))