forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
140_wordBreak2.java
34 lines (30 loc) · 1.08 KB
/
140_wordBreak2.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
public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
return dfs(s, wordDict, map);
}
public List<String> dfs(String s, Set<String> wordDict, HashMap<String, List<String>> map){
if(map.containsKey(s)) {
return map.get(s);
}
List<String> res = new ArrayList<String>();
if(s.length() == 0){
res.add("");
return res;
}
for(String word: wordDict){
if(s.startsWith(word)){
List<String> remainList = dfs(s.substring(word.length()), wordDict, map);
for(String remain: remainList){
StringBuffer sb = new StringBuffer();
sb.append(word);
if(remain.length() != 0) sb.append(" ");
sb.append(remain);
res.add(sb.toString());
}
}
}
map.put(s, res);
return res;
}
}