|
1 | 1 | class Solution {
|
2 | 2 | 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>>()); |
7 | 4 | }
|
8 | 5 |
|
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) { |
10 | 7 | if (memo.containsKey(s)) {
|
11 | 8 | return memo.get(s);
|
12 | 9 | }
|
13 | 10 |
|
14 | 11 | List<String> result = new ArrayList<>();
|
15 |
| - if (dict.contains(s)) { |
16 |
| - result.add(s); |
17 |
| - } |
18 | 12 |
|
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 | + } |
21 | 19 |
|
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); |
24 | 21 |
|
25 |
| - for (String remainder : tmp) { |
26 |
| - result.add(word + " " + remainder); |
| 22 | + for (String str : postfix) { |
| 23 | + result.add(word + " " + str); |
27 | 24 | }
|
28 | 25 | }
|
29 | 26 | }
|
30 | 27 |
|
31 | 28 | memo.put(s, result);
|
32 |
| - return result; |
| 29 | + return memo.get(s); |
33 | 30 | }
|
34 | 31 | }
|
0 commit comments