-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
41 lines (39 loc) · 1.1 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
38
39
40
41
class Trie {
Trie[] children = new Trie[26];
boolean isEnd = false;
void insert(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
node.children[c] = new Trie();
}
node = node.children[c];
}
node.isEnd = true;
}
}
class Solution {
public int[][] indexPairs(String text, String[] words) {
Trie trie = new Trie();
for (String w : words) {
trie.insert(w);
}
int n = text.length();
List<int[]> ans = new ArrayList<>();
for (int i = 0; i < n; ++i) {
Trie node = trie;
for (int j = i; j < n; ++j) {
int idx = text.charAt(j) - 'a';
if (node.children[idx] == null) {
break;
}
node = node.children[idx];
if (node.isEnd) {
ans.add(new int[] {i, j});
}
}
}
return ans.toArray(new int[ans.size()][2]);
}
}