-
Notifications
You must be signed in to change notification settings - Fork 30
/
break.py
45 lines (37 loc) · 1.49 KB
/
break.py
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
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
# check if wordDict is empty
if not wordDict:
return False
# create list of intervals where words in wordDict are found in s
intervals = []
for word in wordDict:
start_index = 0
while True:
try:
index = s.index(word, start_index)
except ValueError:
break
intervals.append([index, index + len(word) - 1])
start_index = index + 1
# sort intervals by start index
intervals.sort()
# use set to keep track of possible start indices of remaining words
possible_starts = {0}
for interval in intervals:
start, end = interval
# check if current interval starts at a possible start index
if start in possible_starts:
# check if current interval ends at the end of s
if end == len(s) - 1:
return True
# add end index of current interval as a possible start index
possible_starts.add(end + 1)
return False
if __name__ == '__main__':
Instant = Solution()
Solve = Instant.wordBreak("applepenapple", ["apple","pen"])
# s = "applepenapple", wordDict = ["apple","pen"]-> True
# s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] -> False
print(Solve)