前缀树(字典树)
力扣208.实现一棵前缀树
class Trie { // 前缀树的节点 class TrieNode { boolean isWord = false; // 表示该节点是否是单词的最后一个字符 TrieNode[] children; public TrieNode() { children = new TrieNode[26]; } } TrieNode root; // 根节点,作为哨兵 /** Initialize your data structure here. */ public Trie() { root = new TrieNode(); } /** Inserts a word into the trie. */ public void insert(String word) { TrieNode cur = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if (cur.children[index] == null) { // 表示字符还未插入 cur.children[index] = new TrieNode(); } cur = cur.children[index]; } cur.isWord = true; } /** Returns if the word is in the trie. */ public boolean search(String word) { TrieNode cur = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if (cur.children[index] == null) { return false; } cur = cur.children[index]; } if (!cur.isWord) return false; // 走到该节点,还要继续判断以该节点是不是单词的结尾 return true; } /** Returns if there is any word in the trie that starts with the given prefix. */ public boolean startsWith(String prefix) { TrieNode cur = root; for (int i = 0; i < prefix.length(); i++) { int index = prefix.charAt(i) - 'a'; if (cur.children[index] == null) { return false; } cur = cur.children[index]; } return true; } } /** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */
前缀树的应用—连接词
class Solution { // 前缀树节点 class TrieNode { boolean isWord = false; TrieNode[] children; public TrieNode() { children = new TrieNode[26]; } } TrieNode root; private void insert(String word) { TrieNode curr = root; for (int i = 0; i < word.length(); i++) { int index = word.charAt(i) - 'a'; if (curr.children[index] == null) { curr.children[index] = new TrieNode(); } curr = curr.children[index]; } curr.isWord = true; } private boolean search(String word, int cnt) { TrieNode curr = root; if (cnt == word.length()) { return true; } int len = word.length(); for (int i = cnt; i < len; i++) { int index = word.charAt(i) - 'a'; curr = curr.children[index]; if (curr == null) { return false; } if (curr.isWord) { if (search(word, i+1)) return true; } } return false; } public List<String> findAllConcatenatedWordsInADict(String[] words) { List<String> ans = new LinkedList<>(); // 对words进行排序,保证短的word在前 Arrays.sort(words, (x,y) -> (x.length() - y.length())); // 对每个单词进行判断,是连接词,还是组成连接词的单词 int len = words.length; root = new TrieNode(); // 创建前缀树 for (int i = 0; i < len; i++) { String word = words[i]; if (word.length() == 0) continue; if (search(word, 0)) { ans.add(word); } else { insert(word); } } return ans; } }
作者:Ryanjie
出处:http://www.cnblogs.com/ryanjan/
本文版权归作者和博客园所有,欢迎转载。转载请在留言板处留言给我,且在文章标明原文链接,谢谢!
如果您觉得本篇博文对您有所收获,觉得我还算用心,请点击右下角的 [推荐],谢谢!