Skip to content

Commit 902ab32

Browse files
committed
Update 140_Word_Break_II.java
1 parent ee9c12c commit 902ab32

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed
Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,31 @@
11
class Solution {
22
public List<String> wordBreak(String s, List<String> wordDict) {
3-
Set<String> dict = new HashSet<>(wordDict);
4-
Map<String, List<String>> memo = new HashMap<>();
5-
6-
return helper(s, dict, memo);
3+
return dfs(s, new HashSet<String>(wordDict), new HashMap<String, List<String>>());
74
}
85

9-
private List<String> helper(String s, Set<String> dict, Map<String, List<String>> memo) {
6+
private List<String> dfs(String s, Set<String> dict, Map<String, List<String>> memo) {
107
if (memo.containsKey(s)) {
118
return memo.get(s);
129
}
1310

1411
List<String> result = new ArrayList<>();
15-
if (dict.contains(s)) {
16-
result.add(s);
17-
}
1812

19-
for (int i = 1; i < s.length(); i++) {
20-
String word = s.substring(0, i);
13+
for (String word : dict) {
14+
if (s.startsWith(word)) {
15+
if (word.length() == s.length()) {
16+
result.add(word);
17+
continue;
18+
}
2119

22-
if (dict.contains(word)) {
23-
List<String> tmp = helper(s.substring(i), dict, memo);
20+
List<String> postfix = dfs(s.substring(word.length()), dict, memo);
2421

25-
for (String remainder : tmp) {
26-
result.add(word + " " + remainder);
22+
for (String str : postfix) {
23+
result.add(word + " " + str);
2724
}
2825
}
2926
}
3027

3128
memo.put(s, result);
32-
return result;
29+
return memo.get(s);
3330
}
3431
}

0 commit comments

Comments
 (0)