-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreak139.java
More file actions
31 lines (28 loc) · 785 Bytes
/
WordBreak139.java
File metadata and controls
31 lines (28 loc) · 785 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
package medium.string;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class WordBreak139
{
public boolean wordBreak(String s, List<String> wordDict)
{
if (s == null || wordDict == null) {
return false;
}
if (s.length() == 0 && wordDict.size() == 0) {
return true;
}
Set<String> set = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && set.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}