-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathword_break.py
119 lines (91 loc) · 2.69 KB
/
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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# coding = utf-8
def wordBreak(s):
res = []
for i in range(len(s)):
for j in range(i+1,len(s)-1):
word = s[i:j]
if is_word(word):
res.append(word)
if j < len(s):
res.append(wordBreak(s[j:len(s)]))
else:
return res
else:
continue
return res
def is_word(word):
worddict = ['a', 'an', 'any', 'anyone','on','one','bar', 'barks', 'ark', 'bark']
if word in worddict:
return True
else:
return False
def generate_candidate(result):
candidate_set = []
for i in range(0,result.__len__(),2):
content = result[i]
next_set = generate_candidate(result[i+1])
candidate = Candidate(content,next_set)
candidate_set.append(candidate)
return candidate_set
def get_all_candidate(candidate):
candidate_list = []
item = []
item.append(candidate)
flag = True
while flag:
flag = False
if candidate.has_next():
next = candidate.next
for i in next:
if i.flag == 0:
candidate = i
item.append(candidate)
# print(candidate.content)
candidate.flag = 1
flag = True
break
if not flag:
item.pop()
if item.__len__() != 0:
candidate = item.pop()
item.append(candidate)
flag = True
else:
res = []
for i in item:
res.append(i)
candidate_list.append(res)
item.pop()
candidate = item.pop()
item.append(candidate)
flag = True
return candidate_list
class Candidate():
def __init__(self,content, next):
self.content = content
self.next = next
# 0 表示未被遍历
self.flag = 0
def has_next(self):
if len(self.next) == 0:
return False
else:
return True
if __name__ == '__main__':
res = wordBreak("anyonebarks89")
candidate_set = generate_candidate(res)
candidate_set = get_all_candidate(candidate_set[0])
print(candidate_set.__len__())
for item in candidate_set:
for i in item:
print(i.content)
print("-----------")
# for item in candidate_set:
# print(item.content)
# print(len(item.next))
# item_set = []
# item = []
# candidate_set = get_all_candidate(candidate_set[0],item_set,item)
# print(candidate_set)
# for item in candidate_set:
# print(item)