forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
32 lines (31 loc) · 1001 Bytes
/
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
class Trie {
Trie[] children = new Trie[26];
String root;
}
class Solution {
public String replaceWords(List<String> dictionary, String sentence) {
Trie trie = new Trie();
for (String root : dictionary) {
Trie cur = trie;
for (char c : root.toCharArray()) {
if (cur.children[c - 'a'] == null) {
cur.children[c - 'a'] = new Trie();
}
cur = cur.children[c - 'a'];
}
cur.root = root;
}
List<String> ans = new ArrayList<>();
for (String word : sentence.split("\\s+")) {
Trie cur = trie;
for (char c : word.toCharArray()) {
if (cur.children[c - 'a'] == null || cur.root != null) {
break;
}
cur = cur.children[c - 'a'];
}
ans.add(cur.root == null ? word : cur.root);
}
return String.join(" ", ans);
}
}