前缀树 Trie
-
Trie,又称前缀树或字典树,用于判断字符串是否存在或者是否具有某种字符串前缀。
-
一个保存了8个键的trie结构,“A”, “to”, “tea”, “ted”, “ten”, “i”, “in”, and “inn”.
-
在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。(来源:wiki)
-
Trie树的优缺点
Trie树的核心思想是空间换时间,利用字符串的公共前缀来减少无谓的字符串比较以达到提高查询效率的目的。优点
插入和查询的效率很高,都为O(m)O(m),其中 mm 是待插入/查询的字符串的长度。关于查询,会有人说 hash 表时间复杂度是O(1)O(1)不是更快?但是,哈希搜索的效率通常取决于 hash 函数的好坏,若一个坏的 hash 函数导致很多的冲突,效率并不一定比Trie树高。
Trie树中不同的关键字不会产生冲突。Trie树只有在允许一个关键字关联多个值的情况下才有类似hash碰撞发生。
Trie树不用求 hash 值,对短字符串有更快的速度。通常,求hash值也是需要遍历字符串的。
Trie树可以对关键字按字典序排序。
缺点
当 hash 函数很好时,Trie树的查找效率会低于哈希搜索。空间消耗比较大。
class Trie {
/** Initialize your data structure here. */
//build node class
private class Node{
Node[] childs=new Node[26];
boolean isLeaf;
}
// initalize root node
private Node root = new Node();
public Trie() {
}
/** Inserts a word into the trie. */
public void insert(String word) {
insert(word,root);
}
private void insert(String word,Node node){
if (node==null) return;
if (word.length()==0){
node.isLeaf=true;
return;
}
int index=indexForChar(word.charAt(0));
if (node.childs[index]==null){
node.childs[index]=new Node();
}
insert(word.substring(1),node.childs[index]);
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
return search(word,root);
}
private boolean search(String word,Node node){
if (node==null) return false;
if (word.length()==0) return node.isLeaf;
int index=indexForChar(word.charAt(0));
return search(word.substring(1),node.childs[index]);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
return startsWith(prefix,root);
}
private boolean startsWith(String prefix,Node node){
if (node==null) return false;
if (prefix.length()==0) return true;
int index=indexForChar(prefix.charAt(0));
if (node.childs[index]==null) return false;
return startsWith(prefix.substring(1),node.childs[index]);
}
// get char index
private int indexForChar(char c){
return c-'a';
}
}
/**
* 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);
*/