-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJuly30_2020.java
39 lines (30 loc) · 1.14 KB
/
July30_2020.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Word Break II => Memoization and Recursion over substrings
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
return helper(s, wordDict, new HashMap<String, List<String>>());
}
public List<String> helper(String s, List<String> wordDict, Map<String, List<String>> memo) {
if(memo.containsKey(s)){
return memo.get(s);
}
List<String> results = new ArrayList<>();
// base case
if(s.length() == 0) {
results.add("");
return results;
}
for(String word : wordDict) {
if(s.startsWith(word)){
String subString = s.substring(word.length());
List<String> subStrings = helper(subString, wordDict, memo);
System.out.println(subStrings);
for(String sub : subStrings) {
String space = sub.isEmpty() ? "" : " ";
results.add(word + space + sub);
}
}
}
memo.put(s, results);
return results;
}
}