-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathWordBreak.py
More file actions
123 lines (106 loc) · 3.3 KB
/
WordBreak.py
File metadata and controls
123 lines (106 loc) · 3.3 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
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
115
116
117
118
119
120
121
122
123
# 139. Word Break
# 140. Word Break II
class Solution:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
if not s:
return False
length = len(s)
# dp(n)代表长度为n的单词是否可分,如果可分,则最后长度为i的单词出现在dict中,同时dp(n-i) = True
dp = [False] * (length + 1)
dp[0] = True
for i in range(length):
for j in reversed(range(i+1)):
# 从长度为i的单词末尾向前寻找出现在dict中的单词
sub = s[j:i+1]
if sub in wordDict and dp[j]:
dp[i+1] = True
break
return dp[length]
# Backtracking方法:Leetcode超时
def wordSplit(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
if not s:
return []
dict = {}
for word in wordDict:
if dict.get(word):
dict[word] += 1
else:
dict[word] = 1
res = []
if dict.get(s):
res.append(s)
for i in range(len(s)):
if dict.get(s[:i+1]):
post = self.wordSplit(s[i+1:], wordDict)
if post:
for str in post:
res.append(s[:i+1]+" "+str)
return res
# DP+DFS方法:LeetCode超时
def wordBreakDp(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
if not s:
return []
n = len(s)
# dp[i]记录了s的前i位的workBreak解的最后一个单词的集合
dp = []
dp.append([])
for i in range(1, n+1):
first = s[:i]
dp.append([])
for length in range(i):
if first[i-1-length:] in wordDict:
dp[i].append(first[i-1-length:])
return self.dfs(s, dp)
def dfs(self, s, dp):
if not s:
return []
res = []
if dp[len(s)]:
for word in dp[len(s)]:
if word == s:
res.append(word)
else:
prev = self.dfs(s[:(len(s) - len(word))], dp)
if prev:
for str in prev:
res.append(str+" "+word)
return res
class Solution2:
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
if not s:
return []
n = len(s)
maxLen = max(list(map(lambda x:len(x), wordDict)))
# dp[i]记录了s的前i位的workBreak解的最后一个单词的集合,若不存在则dp[i]为空集
dp = []
for i in range(n):
dp.append([])
for j in reversed(range(i-maxLen, i+1)):
if s[j:i+1] in wordDict:
if j == 0:
dp[i].append(s[j:i+1])
elif dp[j-1]:
for prev in dp[j-1]:
dp[i].append(prev +" "+s[j:i+1])
print(i, len(dp[i]))
return dp[n-1]