-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path140.word-break-ii.java
More file actions
58 lines (53 loc) · 1.91 KB
/
Copy path140.word-break-ii.java
File metadata and controls
58 lines (53 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.ArrayList;
/*
* @lc app=leetcode id=140 lang=java
*
* [140] Word Break II
*/
// @lc code=start
class Solution {
public List<String> wordBreak(String s, List<String> wordDict) {
Map<String, List<String>> dp = new HashMap<>();
Set<String> wordSet = new HashSet<>();
for (String word: wordDict) {
wordSet.add(word);
}
return wordBreakHelper(s, wordSet, dp);
}
private List<String> wordBreakHelper(String s, Set<String> wordSet, Map<String, List<String>> dp) {
// 如果当前string已经遍历过,直接返回之前的结果
if (dp.containsKey(s)) {
return dp.get(s);
}
List<String> resList = new ArrayList<>();
// 如果当前字符是空,表明结束了
// 放一个空字符结束
if (s.isEmpty()) {
resList.add("");
return resList;
}
// 把s分成0 - i 和 i - s结尾
for (int i = 0; i <= s.length(); i++) {
String frontStr = s.substring(0, i);
String laterStr = s.substring(i);
// 如果前半部分在词典里,则找出后半部分的所有组合
if (wordSet.contains(frontStr)) {
List<String> wordList = wordBreakHelper(laterStr, wordSet, dp);
// 把后半部分所有组合的结果和当前词语加起来
for (String word : wordList) {
// 一定要在s是空的时候放空字符
// 这样才能在结尾是空的时候把当前前半部分加进去
if (word.isEmpty()) {
resList.add(frontStr);
}
else {
resList.add(frontStr + ' ' + word);
}
}
}
}
dp.put(s, resList);
return resList;
}
}
// @lc code=end