-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path140. Word Break II.java
38 lines (38 loc) · 1.15 KB
/
140. Word Break II.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
class Solution {
public static class Trie {↔}
public List<String> wordBreak(String s, List<String> wordDict) {
Trie trie = new Trie();
for (String b : wordDict)
trie.insertWord(b);
Map<String, List<String>> map = new HashMap<>();
return wordBreak(s, trie, map);
}
private List<String> wordBreak(String s, Trie trie, Map<String, List<String>> map) {
List<String> ans = new ArrayList<>();
if (map.containsKey(s)) {
return map.get(s);
}
if (trie.search(s)) {
ans.add(s);
}
for (int i = 1; i < s.length(); i++) {
String fpart = s.substring(0, i);
if (trie.search(fpart)) {
String ros = s.substring(i, s.length());
List<String> bbres = wordBreak(ros, trie, map);
for (String r : bbres)
ans.add(fpart + " " + r);
}
}
map.putIfAbsent(s, ans);
return ans;
}
}