字典树 Trie
又称单词查找树或者键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(不仅限于字符串),经常被搜索系统用于文本词频统计
它的优点是:最大限度的减少无谓的字符串比较,查询效率比哈希表高。
基本性质
- 结点本身不存完整单词
- 从根结点到某一结点,路径上经过的字符连接起来,为该结点所对应的字符串
- 每个结点所有的子结点路劲代表的字符都不同
核心思想
Trie树核心思想为空间换时间
利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
字典树的Java实现
首先对字典树结点进行定义和方法,这里只是有26个小写字母的范围
isEnd()方法,用来判断子节点的这个是否为键 或者是字符串的前缀
class TreeNode {
private TreeNode[] links;
private final int R = 26;
private boolean isEnd;
/** Initialize your data structure here. */
public TreeNode() {
links = new TreeNode[R];
}
public boolean containsKey (char ch) {
return links[ch - 'a'] != null;
}
public TreeNode get (char ch) {
return links[ch - 'a'];
}
public void put (char ch, TreeNode node) {
links[ch - 'a'] = node;
}
public boolean isEnd() {
return isEnd;
}
public void setEnd() {
isEnd = true;
}
}
字典树的实现
class Trie {
private TreeNode root;
public Trie() {
root = new TreeNode();
}
/** Inserts a word into the trie. */
public void insert(String word) { //插入键
TreeNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!node.containsKey(ch)) {
node.put(ch, new TreeNode());
}
node = node.get(ch);
}
node.setEnd();
}
/** Returns if the word is in the trie. */
public TreeNode searchStr(String word) { //查找字符串
TreeNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (node.containsKey(ch)) {
node = node.get(ch);
} else {
return null;
}
}
return node;
}
public boolean search (String word) { //查找键
TreeNode node = searchStr(word);
return node != null && node.isEnd();
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) { //查找前缀
TreeNode node = searchStr(prefix);
return node != null;
}
}
复杂度分析
插入操作
时间复杂度:O(m),其中 m 为键长。在算法的迭代中,我们要么检查要么创建一个节点,直到到达键尾。只需要 mm次操作。
空间复杂度:O(m)。最坏的情况下,新插入的键和 Trie 树中已有的键没有公共前缀。此时需要添加 m个结点,使用 O(m)空间。
查找操作
时间复杂度 : O(m)。算法的每一步均搜索下一个键字符。最坏的情况下需要 m次操作。
空间复杂度 : O(1)。