Skip to content

Commit 2e36ed3

Browse files
committed
Updated word break 2
1 parent 396d1e1 commit 2e36ed3

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed

Hard/WordBreak2.java

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,16 @@ public List<String> wordBreak(String s, Set<String> dict) {
3737

3838
int len = s.length();
3939
for (int i = 1; i <= len; i++) {
40-
String prefix = s.substring(0, i); // get prefix
41-
if (dict.contains(prefix)) { // is in dictionary
42-
if (i == len) words.add(prefix); // reach the end
40+
String pref = s.substring(0, i);
41+
if (dict.contains(pref)) {
42+
if (i == len) words.add(pref); // reach the end
4343
else {
44-
String remain = s.substring(i, len); // rest of the string
44+
String remain = s.substring(i, len); // remaining string
4545
List<String> remainDecomp = res.containsKey(remain) ?
4646
res.get(remain) : wordBreak(remain, dict); // avoid backtracking if a decomposition is already there
4747
if (remainDecomp != null) {
48-
for (String w : remainDecomp) words.add(prefix + " " + w);
49-
res.put(remain, remainDecomp); // add to memory func
48+
for (String w : remainDecomp) words.add(pref + " " + w);
49+
res.put(remain, remainDecomp); // add to cache
5050
}
5151
}
5252
}
@@ -55,24 +55,28 @@ public List<String> wordBreak(String s, Set<String> dict) {
5555
}
5656

5757
/**
58-
* Simple backtracking
58+
* Backtracking
59+
* Get prefix first
60+
* If prefix is in dictionary, check current length
61+
* If reaches the end, add prefix to result
62+
* If not, go ahead and decompose the remain string
63+
* Get the result list, and concat prefix with those results
64+
* Add the concatenated string to result and return
5965
*/
6066
public List<String> wordBreak(String s, Set<String> dict) {
6167
List<String> words = new ArrayList<String>();
6268

6369
int len = s.length();
6470
for (int i = 1; i <= len; i++) {
65-
String prefix = s.substring(0, i);
66-
if (dict.contains(prefix)) {
67-
if (i == len) {
68-
words.add(prefix); // single word
69-
} else {
71+
String pref = s.substring(0, i);
72+
if (dict.contains(pref)) {
73+
if (i == len) words.add(pref);
74+
else {
7075
String remain = s.substring(i, len);
71-
// backtracking
7276
List<String> remainDecomp = wordBreak(remain, dict);
73-
if (remainDecomp != null) { // has decomposition
77+
if (remainDecomp != null) { // has decompositions
7478
for (String item : remainDecomp) {
75-
words.add(prefix + " " + item); // item is already words with spaces between
79+
words.add(pref + " " + item);
7680
}
7781
}
7882
}

0 commit comments

Comments
 (0)