Skip to content

Commit 2cce238

Browse files
committed
Update Word Break II.py
Instead of two passes, we might do it in one pass, and decide whether we need to backtrack all the paths. Please let me know if you have any thoughts on it. Thanks!
1 parent 93a8f22 commit 2cce238

File tree

1 file changed

+25
-27
lines changed

1 file changed

+25
-27
lines changed

Word Break II.py

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,26 @@
1-
class Solution:
2-
def canBreak(self, s, dict):
3-
possible = []
4-
for i in range(len(s)):
5-
if s[:i + 1] in dict:
6-
possible.append(True)
7-
else:
8-
found = False
9-
for j in range(i):
10-
if possible[j] == True and s[j + 1: i + 1] in dict:
11-
found = True
12-
break
13-
possible.append(found)
14-
return possible[len(s) - 1]
15-
1+
class Solution:
162
def wordBreak(self, s, dict):
17-
result = {}
18-
if not self.canBreak(s, dict):
19-
return []
20-
for i in range(len(s)):
21-
result[s[:i + 1]] = []
22-
if s[:i + 1] in dict:
23-
result[s[:i + 1]] = [s[:i + 1]]
24-
for j in range(i):
25-
if s[:j + 1] in result and s[j + 1: i + 1] in dict:
26-
for k in result[s[:j + 1]]:
27-
result[s[:i + 1]].append(k + " " + s[j + 1: i + 1])
28-
return result[s]
3+
n = len(s)
4+
f = [False for _ in xrange(n)]
5+
trace = [[False] * n for _ in xrange(n)]
6+
for i in xrange(n):
7+
trace.append([])
8+
if s[:i+1] in dict:
9+
f[i] = True
10+
trace[0][i] = True
11+
for j in xrange(i):
12+
if f[j] and s[j+1:i+1] in dict:
13+
f[i] = True
14+
trace[j+1][i] = True
15+
result = []
16+
if f[n-1]:
17+
self.backtrack(s, trace, 0, [], result)
18+
return result
19+
20+
def backtrack(self, s, trace, start, path, result):
21+
if start == len(s):
22+
result.append(" ".join(path))
23+
return
24+
for i in xrange(start, len(s)):
25+
if trace[start][i]:
26+
self.backtrack(s, trace, i + 1, path + [s[start:i+1]], result)

0 commit comments

Comments
 (0)