-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreak2.java
More file actions
62 lines (47 loc) · 1.19 KB
/
WordBreak2.java
File metadata and controls
62 lines (47 loc) · 1.19 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.*;
public class WordBreak2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public List<String> wordBreak(String s, Set<String> dict) {
List<String> retList = new ArrayList<String>();
List<String> changingList = new ArrayList<String>();
worker(retList, changingList, dict, s);
return retList;
}
public void worker(List<String> retList, List<String> changingList, Set<String> dict, String pendingString)
{
for(int i = 1; i<= pendingString.length(); i++ )
{
String ss = pendingString.substring(0, i);
if(dict.contains(ss))
{
changingList.add(ss);
dict.remove(ss);
if(i == pendingString.length())
{
retList.add(generateString(changingList));
}
else
{
worker(retList, changingList, dict, pendingString.substring(i));
}
dict.add(ss);
changingList.remove(ss);
}
}
}
public String generateString(List<String> changingList)
{
if(changingList.size() == 0) return "";
String ret = "";
for(int i=0; i<changingList.size() ; i++)
{
ret += changingList.get(i) + " ";
}
return ret.substring(0, ret.length()-1);
}
}