Skip to content

Commit f6f6a00

Browse files
committed
wordBreak, wordBreak.II
1 parent ffae07f commit f6f6a00

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/wordBreak/wordBreak.II.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
public class Solution {
2+
public List<String> wordBreak(String s, Set<String> dict) {
3+
List<String> results = new LinkedList<String>();
4+
if (dict.size() == 0 || s.length() == 0) { return results; }
5+
int sl = s.length();
6+
ArrayList<LinkedList<Integer>> dp = new ArrayList<LinkedList<Integer>>(sl);
7+
for (int i=0; i<sl; i++) {
8+
dp.add(null);
9+
}
10+
for (int i=sl-1; i>=0; i--) {
11+
for (int j=i+1; j<=sl; j++) {
12+
if (dict.contains(s.substring(i, j))) {
13+
if (j == sl || dp.get(j) != null) {
14+
if (dp.get(i) == null) {
15+
dp.set(i, new LinkedList<Integer>());
16+
}
17+
dp.get(i).add(j);
18+
}
19+
}
20+
}
21+
}
22+
if (dp.get(0) == null) {
23+
return results;
24+
}
25+
26+
generate(s, dp, 0, new StringBuilder(), results);
27+
return results;
28+
}
29+
30+
public void generate(String s, ArrayList<LinkedList<Integer>> dp, int index, StringBuilder sb, List<String> results) {
31+
if (index == s.length()) {
32+
results.add(sb.toString());
33+
return;
34+
}
35+
LinkedList<Integer> list = dp.get(index);
36+
for (int next: list) {
37+
StringBuilder newSb = new StringBuilder(sb);
38+
newSb.append(s.substring(index, next));
39+
if (next != s.length()) {
40+
newSb.append(" ");
41+
}
42+
generate(s, dp, next, newSb, results);
43+
}
44+
}
45+
}

src/wordBreak/wordBreak.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
public class Solution {
2+
public boolean wordBreak(String s, Set<String> dict) {
3+
HashSet<String> cache = new HashSet<String>();
4+
return wordBreak(s, dict, cache);
5+
}
6+
public boolean wordBreak(String s, Set<String> dict, HashSet<String> cache) {
7+
if (cache.contains(s)) {
8+
return false;
9+
}
10+
int sl = s.length();
11+
if (sl == 0) {
12+
return true;
13+
}
14+
StringBuilder sb = new StringBuilder();
15+
for (int i=0; i<sl; i++) {
16+
char c = s.charAt(i);
17+
sb.append(c);
18+
if (dict.contains(sb.toString())) {
19+
String newStr = s.substring(i+1);
20+
if (wordBreak(newStr, dict, cache)) {
21+
return true;
22+
} else {
23+
cache.add(newStr);
24+
}
25+
}
26+
}
27+
return false;
28+
}
29+
}

0 commit comments

Comments
 (0)