-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path139.word-break.java
More file actions
33 lines (30 loc) · 860 Bytes
/
Copy path139.word-break.java
File metadata and controls
33 lines (30 loc) · 860 Bytes
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
import java.util.HashSet;
import java.util.List;
/*
* @lc app=leetcode id=139 lang=java
*
* [139] Word Break
*/
// @lc code=start
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
// dp[i] 表示范围 [0, i) 内的子串是否可以拆分
// [0, i) 分为 [0, j) 和 [j, i)
boolean[] dp = new boolean[s.length() + 1];
Set<String> wordSet = new HashSet<>();
for (String word: wordDict) {
wordSet.add(word);
}
dp[0] = true;
for (int i = 0; i <= s.length(); i++) {
// 把s分成0 - j 和 j - i
for (int j = 0; j < i; j++) {
if (dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
}
}
}
return dp[s.length()];
}
}
// @lc code=end