-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path140.java
More file actions
26 lines (25 loc) · 868 Bytes
/
140.java
File metadata and controls
26 lines (25 loc) · 868 Bytes
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
//DFS + HashMap
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
Map<String, List<String>> map = new HashMap<>();
return find(s, wordDict, map);
}
public List<String> find(String s, List<String> wordDict, Map<String, List<String>> map) {
if (map.containsKey(s)) return map.get(s);
List<String> ans = new ArrayList<String>();
if (s.length() == 0) {
ans.add("");
return ans;
}
for (String word : wordDict) {
if (s.startsWith(word)) {
List<String> cur = find(s.substring(word.length()), wordDict, map);
for (String newStr : cur) {
ans.add(word + (newStr.isEmpty() ? "" : " ") + newStr);
}
}
}
map.put(s, ans);
return ans;
}
}