- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWordBreak.py
More file actions
Latest commit
89 lines (73 loc) · 1.79 KB
/
Copy pathWordBreak.py
File metadata and controls
89 lines (73 loc) · 1.79 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
'''
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".
'''
DICT=["cat", "cats", "and", "sand", "dog"]
defis_word(word):
returnwordinDICT
'''
given the string and dictionary,
check whether the string can be space-seperated sentence
Args: string
Return: True or False
'''
defword_break(s):
ifnots:
returnTrue
else:
foriinrange(len(s)):
# string slicing
word=s[0:i+1]
ifis_word(word):
rest=s[i+1:]
ifword_break(rest):
returnTrue
# defaul there is no solution
returnFalse
# check wether it is empty string
defword_break_no_empty(s):
ifnots:
returnFalse
else:
returnword_break(s)
'''
Given a string s and a dictionary of words dict,
add spaces in s to construct a sentence
where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
'''
'''
construct a sentense with space-separated words based on the given string
and dictionary
Args: string
Return: list of sentences
'''
defsolver(s):
results= []
ifnots:
results.append('')
else:
foriinrange(len(s)):
word=s[0:i+1]
ifis_word(word):
sub_sentences=solver(s[i+1:])
forsentenceinsub_sentences:
# append the first word
results.append(word+' '+sentence )
returnresults
defmain():
test1='leetcode'
test2='catsanddog'
printword_break_no_empty(test2)
printsolver(test2)
# print results
main()