forked from yuanguangxin/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
49 lines (42 loc) · 1.26 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
package 字典树.q648_单词替换;
import java.util.List;
/**
* 构建字典树(前缀树)o(n)
*/
class Solution {
public String replaceWords(List<String> roots, String sentence) {
TrieNode trie = new TrieNode();
for (String root : roots) {
TrieNode cur = trie;
for (char letter : root.toCharArray()) {
if (cur.children[letter - 'a'] == null) {
cur.children[letter - 'a'] = new TrieNode();
}
cur = cur.children[letter - 'a'];
}
cur.word = root;
}
StringBuilder ans = new StringBuilder();
for (String word : sentence.split(" ")) {
if (ans.length() > 0) {
ans.append(" ");
}
TrieNode cur = trie;
for (char letter : word.toCharArray()) {
if (cur.children[letter - 'a'] == null || cur.word != null) {
break;
}
cur = cur.children[letter - 'a'];
}
ans.append(cur.word != null ? cur.word : word);
}
return ans.toString();
}
}
class TrieNode {
TrieNode[] children;
String word;
TrieNode() {
children = new TrieNode[26];
}
}