forked from dimitar9/Algorithm_Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT140_work_break_2.java
More file actions
28 lines (27 loc) · 795 Bytes
/
T140_work_break_2.java
File metadata and controls
28 lines (27 loc) · 795 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
27
28
public class Solution {
public List<String> wordBreak(String s, Set<String> dict) {
List<String> result = new ArrayList<String>();
for(int j = s.length() - 1; j >= 0; j--){
if(dict.contains(s.substring(j)))
break;
else{
if(j == 0)
return result;
}
}
for(int i = 0; i < s.length()-1; i++)
{
if(dict.contains(s.substring(0,i+1)))
{
List<String> strs = wordBreak(s.substring(i+1,s.length()),dict);
if(strs.size() != 0)
for(Iterator<String> it = strs.iterator();it.hasNext();)
{
result.add(s.substring(0,i+1)+" "+it.next());
}
}
}
if(dict.contains(s)) result.add(s);
return result;
}
}