-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
46 lines (46 loc) · 1.48 KB
/
Solution.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
40
41
42
43
44
45
46
public class Solution {
Map<String,List<String>> map=new HashMap<String, List<String>>();
Map<String,Boolean> bmap=new HashMap<String, Boolean>();
public List<String> wordBreak(String s, Set<String> wordDict) {
List<String> list=new ArrayList<String>();
if(s==null||s.length()==0){
return list;
}
if (map.get(s)!=null) {
return map.get(s);
}
if(bmap.get(s)!=null){
return null;
}
for (int i = 0; i < s.length()-1; i++) {
String k=s.substring(0,i+1);
if(wordDict.contains(k)){
String t=s.substring(i+1,s.length());
if(bmap.get(t)==null){
List<String> l=map.get(t);
if (l!=null) {
for (int j = 0; j < l.size(); j++) {
list.add(k+" "+l.get(j));
}
}else {
List<String> a=wordBreak(t,wordDict);
if (a!=null) {
for (int j = 0; j < a.size(); j++) {
list.add(k+" "+a.get(j));
}
}
}
}
}
}
if(wordDict.contains(s)){
list.add(s);
}
if (list.size()==0) {
bmap.put(s, false);
return list;
}
map.put(s, list);
return list;
}
}