Skip to content

Commit fab3f93

Browse files
Added Day-30 Solution
1 parent d20ea06 commit fab3f93

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Day-30_Word_Break_II.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
'''
2+
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
3+
4+
Note:
5+
6+
The same word in the dictionary may be reused multiple times in the segmentation.
7+
You may assume the dictionary does not contain duplicate words.
8+
Example 1:
9+
10+
Input:
11+
s = "catsanddog"
12+
wordDict = ["cat", "cats", "and", "sand", "dog"]
13+
Output:
14+
[
15+
"cats and dog",
16+
"cat sand dog"
17+
]
18+
Example 2:
19+
20+
Input:
21+
s = "pineapplepenapple"
22+
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
23+
Output:
24+
[
25+
"pine apple pen apple",
26+
"pineapple pen apple",
27+
"pine applepen apple"
28+
]
29+
Explanation: Note that you are allowed to reuse a dictionary word.
30+
Example 3:
31+
32+
Input:
33+
s = "catsandog"
34+
wordDict = ["cats", "dog", "sand", "and", "cat"]
35+
Output:
36+
[]
37+
38+
'''
39+
40+
class Solution:
41+
def wordBreak(self, s, wordDict):
42+
wordSet = set(wordDict)
43+
n = len(s)
44+
dp_solution = [[] for _ in range(n)] + [[""]]
45+
dp = [0] * n + [1]
46+
47+
for k in range(n):
48+
for j in range(k,-1,-1):
49+
if s[j: k + 1] in wordSet:
50+
dp[k] = max(dp[k], dp[j-1])
51+
52+
if dp[-2] == 0: return []
53+
54+
for k in range(n):
55+
for j in range(k,-1,-1):
56+
if s[j: k + 1] in wordSet:
57+
for sol in dp_solution[j-1]:
58+
dp_solution[k].append(sol + " " + s[j: k + 1])
59+
60+
return [s[1:] for s in dp_solution[-2]]

0 commit comments

Comments
 (0)