@@ -37,16 +37,16 @@ public List<String> wordBreak(String s, Set<String> dict) {
37
37
38
38
int len = s .length ();
39
39
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
43
43
else {
44
- String remain = s .substring (i , len ); // rest of the string
44
+ String remain = s .substring (i , len ); // remaining string
45
45
List <String > remainDecomp = res .containsKey (remain ) ?
46
46
res .get (remain ) : wordBreak (remain , dict ); // avoid backtracking if a decomposition is already there
47
47
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
50
50
}
51
51
}
52
52
}
@@ -55,24 +55,28 @@ public List<String> wordBreak(String s, Set<String> dict) {
55
55
}
56
56
57
57
/**
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
59
65
*/
60
66
public List <String > wordBreak (String s , Set <String > dict ) {
61
67
List <String > words = new ArrayList <String >();
62
68
63
69
int len = s .length ();
64
70
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 {
70
75
String remain = s .substring (i , len );
71
- // backtracking
72
76
List <String > remainDecomp = wordBreak (remain , dict );
73
- if (remainDecomp != null ) { // has decomposition
77
+ if (remainDecomp != null ) { // has decompositions
74
78
for (String item : remainDecomp ) {
75
- words .add (prefix + " " + item ); // item is already words with spaces between
79
+ words .add (pref + " " + item );
76
80
}
77
81
}
78
82
}
0 commit comments