Skip to content

Commit 6321562

Browse files
Alagappan MaruthappanAlagappan Maruthappan
Alagappan Maruthappan
authored and
Alagappan Maruthappan
committed
word break problem
1 parent e8467f1 commit 6321562

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

word_break.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# https://leetcode.com/problems/word-break/description/
2+
3+
4+
class Solution:
5+
def __init__(self):
6+
self.soln = []
7+
8+
def wordBreakUtil(self, s, wordDict, cache, start_index, soln):
9+
"""
10+
:type s: str
11+
:type wordDict: List[str]
12+
:rtype: bool
13+
"""
14+
if start_index >= len(s):
15+
self.soln.append(soln)
16+
if not cache[start_index] is None:
17+
return cache[start_index]
18+
ans = False
19+
for index in range(start_index+1, len(s) + 1):
20+
word = s[start_index:index]
21+
if word in wordDict:
22+
soln.append(word)
23+
self.wordBreakUtil(s, wordDict, cache, index, soln)
24+
soln.pop()
25+
cache[start_index] = ans
26+
27+
def wordBreak(self, s, wordDict):
28+
cache = [None] * len(s)
29+
return self.wordBreakUtil(s, wordDict, cache, 0, [])
30+
31+
32+
s = "leetcode"
33+
wordDict = ["leet", "code"]
34+
assert Solution().wordBreak(s, wordDict)
35+
36+
s = "catsandog"
37+
wordDict = ["cats", "dog", "sand", "and", "cat"]
38+
assert not Solution().wordBreak(s, wordDict)
39+
40+
s = "applepenapple"
41+
wordDict = ["apple", "pen"]
42+
assert Solution().wordBreak(s, wordDict)

0 commit comments

Comments
 (0)