forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
63 lines (59 loc) · 1.64 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution {
public int[][] multiSearch(String big, String[] smalls) {
Trie tree = new Trie();
int n = smalls.length;
for (int i = 0; i < n; ++i) {
tree.insert(smalls[i], i);
}
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; ++i) {
res.add(new ArrayList<>());
}
for (int i = 0; i < big.length(); ++i) {
String s = big.substring(i);
List<Integer> t = tree.search(s);
for (int idx : t) {
res.get(idx).add(i);
}
}
int[][] ans = new int[n][];
for (int i = 0; i < n; ++i) {
ans[i] = res.get(i).stream().mapToInt(Integer::intValue).toArray();
}
return ans;
}
}
class Trie {
private int idx;
private Trie[] children;
public Trie() {
idx = -1;
children = new Trie[26];
}
public void insert(String word, int i) {
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.idx = i;
}
public List<Integer> search(String word) {
Trie node = this;
List<Integer> res = new ArrayList<>();
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return res;
}
node = node.children[c];
if (node.idx != -1) {
res.add(node.idx);
}
}
return res;
}
}