forked from ritiek/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
word_break.py
44 lines (34 loc) · 915 Bytes
/
word_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
"""
Given a non-empty string s and a dictionary wordDict
containing a list of non-empty words,
determine if s can be segmented into a space-separated
sequence of one or more dictionary words.
You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
"""
"""
s = abc word_dict = ["a","bc"]
True False False False
"""
# TC: O(N^2) SC: O(N)
def word_break(s, word_dict):
"""
:type s: str
:type word_dict: Set[str]
:rtype: bool
"""
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(0, i):
if dp[j] and s[j:i] in word_dict:
dp[i] = True
break
return dp[-1]
if __name__ == "__main__":
s = "keonkim"
dic = ["keon", "kim"]
print(word_break(s, dic))