-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword_break.py
More file actions
59 lines (38 loc) · 1.25 KB
/
word_break.py
File metadata and controls
59 lines (38 loc) · 1.25 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
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
"""
def word_break_2(word, dict):
for i in range(len(word)):
first = word[:i]
second = word[i:]
if first in dict and second in dict:
return True
return False
print(word_break_2("leetcode", ["leet", "code"]))
dict = ["leet", "code", "is", "great", "mark", "for"]
string = "leetcodeismark"
# More general case.
def word_break(string, dict):
words = []
def find_words(string):
for i in range(len(string)+1):
prefix = string[:i]
if prefix in dict:
words.append(prefix)
find_words(string[i:])
find_words(string)
return " ".join(words)
print(word_break(string, dict))
# without closure
def word_break_3(string, dict):
if string in dict: return [string]
for i in range(len(string)+1):
prefix = string[:i]
if prefix in dict:
return [prefix] + word_break_3(string[i:], dict)
return []
print(" ".join(word_break_3(string, dict)))