LeetCode: Word Break

LeetCode: Word Break

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

/**
* Description: 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.
* <p/>
* For example, given s = "leetcode", dict = ["leet", "code"].
* <p/>
* Return true because "leetcode" can be segmented as "leet code".
*
* @author hzhou
*/
public class WordBreak {
public boolean wordBreak(String s, Set<String> wordDict) {
if (s == null || s.isEmpty()) {
return true;
}
boolean[] map = new boolean[s.length() + 1];
map[0] = true;
for (int i = 0; i < s.length(); i++) {
if (!map[i]) {
continue;
}
for (String str : wordDict) {
int l = str.length();
int end = i + l;
if (end > s.length()) {
continue;
}
if (map[end]) {
continue;
}
String sub = s.substring(i, end);
if (sub.equals(str)) {
//if (wordDict.contains(sub)) {
map[end] = true;
}
}
}
return map[s.length()];
}
}