-
-
Notifications
You must be signed in to change notification settings - Fork 146
Expand file tree
/
Copy pathWordBreak.java
More file actions
36 lines (28 loc) · 761 Bytes
/
WordBreak.java
File metadata and controls
36 lines (28 loc) · 761 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
32
33
34
35
36
package leetcode;
import java.util.*;
/**
* Created by nikoo28 on 7/18/19 9:50 PM
*/
class WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
int[] visited = new int[s.length()];
Set<String> dictSet = new HashSet<>(wordDict);
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
while (!queue.isEmpty()) {
Integer begin = queue.remove();
if (visited[begin] == 0) {
for (int i = begin + 1; i <= s.length(); i++) {
String substring = s.substring(begin, i);
if (dictSet.contains(substring)) {
queue.add(i);
if (i == s.length())
return true;
}
}
visited[begin] = 1;
}
}
return false;
}
}