forked from quanjin24k/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreak.java
More file actions
28 lines (23 loc) · 645 Bytes
/
WordBreak.java
File metadata and controls
28 lines (23 loc) · 645 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
import java.util.List;
/**
* https://leetcode.com/articles/word-break/
*/
public class WordBreak {
// 耗时3ms
// 典型的DP问题
public boolean wordBreak(String s, List<String> wordDict) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (String word : wordDict) {
int j = i - word.length();
if (j >= 0 && dp[j] && s.substring(j, i).equals(word)) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
}