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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class Solution { private static class Trie {
private static class TrieNode { private final TrieNode[] children; private String word;
public TrieNode() { this.children = new TrieNode[26]; } }
private final TrieNode root;
public Trie() { this.root = new TrieNode(); }
public void insert(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { int offset = word.charAt(i) - 'a'; if (node.children[offset] == null) { node.children[offset] = new TrieNode(); } node = node.children[offset]; } node.word = word; }
public String getRootWord(String word) { TrieNode node = root; for (int i = 0; i < word.length(); i++) { int offset = word.charAt(i) - 'a'; if (node.children[offset] == null) { return null; } node = node.children[offset]; if (node.word != null) { break; } } return node.word; }
}
public String replaceWords(List<String> dictionary, String sentence) { Trie trie = new Trie(); for (String word : dictionary) { trie.insert(word); }
String[] words = sentence.split(" "); for (int i = 0; i < words.length; i++) { String rootWord = trie.getRootWord(words[i]); if (rootWord != null) { words[i] = rootWord; } }
return String.join(" ", words); } }
|
References
648. Replace Words
剑指 Offer II 063. 替换单词