Skip to content

Commit 34e4e5e

Browse files
author
Tushar Roy
committed
add another method in word break
1 parent 6f7d168 commit 34e4e5e

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

‎src/com/interview/dynamic/BreakMultipleWordsWithNoSpaceIntoSpace.java‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,43 @@ private List<String> wordBreakUtil(String s, Set<String> dict, Map<Integer, List
144144
return words;
145145
}
146146

147+
/**
148+
* Check if any one solution exists.
149+
* https://leetcode.com/problems/word-break/
150+
*/
151+
public boolean wordBreakTopDownOneSolution(String s, Set<String> wordDict) {
152+
Map<Integer, Boolean> dp = new HashMap<>();
153+
int max = 0;
154+
for (String s1 : wordDict) {
155+
max = Math.max(max, s1.length());
156+
}
157+
return wordBreakTopDownOneSolutionUtil(s, wordDict, 0, max, dp);
158+
159+
}
160+
161+
private boolean wordBreakTopDownOneSolutionUtil(String s, Set<String> dict, int start, int max, Map<Integer, Boolean> dp) {
162+
if (start == s.length()) {
163+
return true;
164+
}
165+
166+
if (dp.containsKey(start)) {
167+
return dp.get(start);
168+
}
169+
170+
for (int i = start; i < start + max && i < s.length(); i++) {
171+
String newWord = s.substring(start, i + 1);
172+
if (!dict.contains(newWord)) {
173+
continue;
174+
}
175+
if (wordBreakTopDownOneSolutionUtil(s, dict, i + 1, max, dp)) {
176+
dp.put(start, true);
177+
return true;
178+
}
179+
}
180+
dp.put(start, false);
181+
return false;
182+
}
183+
147184

148185
public static void main(String args[]){
149186
Set<String> dictionary = new HashSet<String>();

0 commit comments

Comments
 (0)