-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution2.java
46 lines (43 loc) · 1.27 KB
/
Solution2.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
class Trie {
private Trie[] children = new Trie[26];
private int ref = -1;
public void insert(String w, int i) {
Trie node = this;
for (int j = 0; j < w.length(); ++j) {
int idx = w.charAt(j) - 'a';
if (node.children[idx] == null) {
node.children[idx] = new Trie();
}
node = node.children[idx];
}
node.ref = i;
}
public int search(String w) {
Trie node = this;
for (int j = 0; j < w.length(); ++j) {
int idx = w.charAt(j) - 'a';
if (node.children[idx] == null) {
return -1;
}
node = node.children[idx];
if (node.ref != -1) {
return node.ref;
}
}
return -1;
}
}
class Solution {
public String replaceWords(List<String> dictionary, String sentence) {
Trie trie = new Trie();
for (int i = 0; i < dictionary.size(); ++i) {
trie.insert(dictionary.get(i), i);
}
List<String> ans = new ArrayList<>();
for (String w : sentence.split("\\s")) {
int idx = trie.search(w);
ans.add(idx == -1 ? w : dictionary.get(idx));
}
return String.join(" ", ans);
}
}