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];
}
}
q648_单词替换
作品《LeetCode题目分类与面试问题整理 - q648_单词替换》由 不喝星巴克 发布于 匠果,转载请注明出处及链接地址:
http://www.jiangguo.net/c/9r6/r1l.html