Skip to content

Commit 804935e

Browse files
committed
feat: word-break-ii challenge
1 parent 1ad4843 commit 804935e

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Challenge: Given a string and a dictionary, return all possible valid sentences that can be formed.
2+
# This challenge requires recursion with memoization to avoid redundant solutions and explore multiple paths.
3+
# Use object-oriented programming and follow the DRY principle.
4+
5+
from word_break import WordBreak
6+
7+
def main():
8+
s = "catsanddog"
9+
word_dict = {"cat", "cats", "and", "sand", "dog"}
10+
wb = WordBreak(s, word_dict)
11+
sentences = wb.word_break()
12+
print("Possible sentences:")
13+
for sentence in sentences:
14+
print(sentence)
15+
16+
if __name__ == "__main__":
17+
main()
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from typing import List, Set, Dict
2+
3+
class WordBreak:
4+
def __init__(self, s: str, word_dict: Set[str]):
5+
self.s = s
6+
self.word_dict = word_dict
7+
self.memo: Dict[int, List[str]] = {}
8+
9+
def word_break(self, start: int = 0) -> List[str]:
10+
if start == len(self.s):
11+
return [""]
12+
13+
if start in self.memo:
14+
return self.memo[start]
15+
16+
sentences = []
17+
for end in range(start + 1, len(self.s) + 1):
18+
word = self.s[start:end]
19+
if word in self.word_dict:
20+
for subsentence in self.word_break(end):
21+
sentence = word + (" " + subsentence if subsentence else "")
22+
sentences.append(sentence)
23+
24+
self.memo[start] = sentences
25+
return sentences

0 commit comments

Comments
 (0)