-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathWordBreak.java
31 lines (28 loc) · 864 Bytes
/
WordBreak.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
package problems.medium;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created by sherxon on 3/3/17.
*/
public class WordBreak {
/**
* We make helper array length of given word+1 and with all fields false.
* The array element is true if such a word exists in dictionary.
*/
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> set = new HashSet<>(wordDict);
boolean[] a = new boolean[s.length() + 1];
a[0] = true;
for (int i = 0; i < a.length; i++) {
if (a[i]) {
for (int j = i + 1; j < a.length; j++) {
if (set.contains(s.substring(i, j)))
a[j] = true;
}
}
if (a[a.length - 1]) return true;
}
return a[a.length - 1];
}
}