-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
58 lines (48 loc) · 1.49 KB
/
Copy pathSolution.java
File metadata and controls
58 lines (48 loc) · 1.49 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.List;
class Solution {
class TrieNode {
TrieNode[] children;
boolean isEnd;
TrieNode() {
this.children = new TrieNode[26];
}
}
public boolean wordBreak(String s, List<String> wordDict) {
char[] arr = s.toCharArray();
int n = arr.length;
TrieNode root = new TrieNode();
populate(root, wordDict);
boolean[] dp = new boolean[n];
for (int i = 0; i < n; i++) {
if (i == 0 || dp[i - 1]) {
TrieNode curr = root;
for (int j = i; j < n; j++) {
int idx = arr[j] - 'a';
if (curr.children[idx] == null) {
break;
}
curr = curr.children[idx];
if (curr.isEnd) {
dp[j] = true;
}
}
}
}
return dp[n-1];
}
private void populate(TrieNode root, List<String> wordDict) {
for (String word : wordDict) {
TrieNode curr = root;
for (int i = 0; i < word.length(); i++) {
int idx = word.charAt(i) - 'a';
if (curr.children[idx] == null) {
curr.children[idx] = new TrieNode();
}
curr = curr.children[idx];
if (i == word.length() - 1) {
curr.isEnd = true;
}
}
}
}
}