-
Notifications
You must be signed in to change notification settings - Fork 57
/
Solution.java
37 lines (34 loc) · 1.03 KB
/
Solution.java
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
/**
* Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated
* sequence of one or more dictionary words.
*
* For example, given
* s = "leetcode",
* dict = ["leet", "code"].
*
* Return true because "leetcode" can be segmented as "leet code".
*/
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
boolean[] matches = new boolean[s.length() + 1];
matches[0] = true;
for (int i = 0; i < s.length(); i++) {
if (!matches[i]) {
continue;
}
for (String word : wordDict) {
int end = i + word.length();
if (end > s.length()) {
continue;
}
if (matches[end]) {
continue;
}
if (s.substring(i, end).equals(word)) {
matches[end] = true;
}
}
}
return matches[s.length()];
}
}