Skip to content

Commit 29c74c1

Browse files
committed
Add back word break II original solution
1 parent bbf0d4a commit 29c74c1

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Word Break II.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,34 @@ def backtrack(self, s, trace, start, path, result):
2424
for i in xrange(start, len(s)):
2525
if trace[start][i]:
2626
self.backtrack(s, trace, i + 1, path + [s[start:i+1]], result)
27+
28+
class Solution:
29+
""" The alternative solution is to precheck before actually break the words.
30+
"""
31+
def canBreak(self, s, dict):
32+
possible = []
33+
for i in range(len(s)):
34+
if s[:i + 1] in dict:
35+
possible.append(True)
36+
else:
37+
found = False
38+
for j in range(i):
39+
if possible[j] == True and s[j + 1: i + 1] in dict:
40+
found = True
41+
break
42+
possible.append(found)
43+
return possible[len(s) - 1]
44+
45+
def wordBreak(self, s, dict):
46+
result = {}
47+
if not self.canBreak(s, dict):
48+
return []
49+
for i in range(len(s)):
50+
result[s[:i + 1]] = []
51+
if s[:i + 1] in dict:
52+
result[s[:i + 1]] = [s[:i + 1]]
53+
for j in range(i):
54+
if s[:j + 1] in result and s[j + 1: i + 1] in dict:
55+
for k in result[s[:j + 1]]:
56+
result[s[:i + 1]].append(k + " " + s[j + 1: i + 1])
57+
return result[s]

0 commit comments

Comments
 (0)