-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
45 lines (42 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
42
43
44
45
class Trie {
Trie[] children = new Trie[26];
String v;
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.v = word;
}
String search(String word) {
Trie node = this;
for (char c : word.toCharArray()) {
c -= 'a';
if (node.children[c] == null) {
return word;
}
node = node.children[c];
if (node.v != null) {
return node.v;
}
}
return word;
}
}
class Solution {
public String replaceWords(List<String> dictionary, String sentence) {
Trie trie = new Trie();
for (String v : dictionary) {
trie.insert(v);
}
List<String> ans = new ArrayList<>();
for (String v : sentence.split("\\s")) {
ans.add(trie.search(v));
}
return String.join(" ", ans);
}
}