一、什么是Trie字典树
Trie字典树(主要用于存储字符串)查找速度主要和它的元素(字符串)的长度相关[O(w)]。
Trie字典树主要用于存储字符串,Trie 的每个 Node 保存一个字符。用链表来描述的话,就是一个字符串就是一个链表。每个Node都保存了它的所有子节点。
使用场景:通讯录高效搜索,专为处理字符串设计的。
比如字典中有n条数据,如果使用树结构,查询的时间复杂度是O(logn),如果有100万条数据的话,logn大约是20,如果有1亿条数据的话,logn大约是30(参考2的N次方计算器)
时间复杂度为:O(w),w为单词的长度。
例如我们往字典树中插入cat、dog、deef、panda四个单词,Trie字典树如下所示:
也就是说如果只考虑小写的26个字母,那么Trie字典树的每个节点都可能有26个子节点。
二、Trie字典树的基本操作
1、插入
本文是使用链表来实现Trie字典树,字符串的每个字符作为一个Node节点,Node主要有两部分组成:
- 是否是单词 (boolean isWord)
- 节点所有的子节点,用map来保存 (Map next)
例如插入一个paint单词,如果用户查询pain,尽管 paint 包含了 pain,但是Trie中仍然不包含 pain 这个单词,所以如果往Trie中插入一个单词,需要把该单词的最后一个字符的节点的 isWord 设置为 true。所以为什么Node需要存储 是否是单词 这个属性。
节点的所有子节点,通过一个Map来存储,key是当前子节点对应的字符,value是子节点。
import java.util.TreeMap;
public class Trie {
private class Node{
public boolean isWord; // 是否是单词 (boolean isWord)
// 节点所有的子节点,用map来保存 (Map next)
public TreeMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new TreeMap<>();
}
public Node(){
this(false);
}
}
private Node root;
private int size; // 存储单词的个数
public Trie(){
root = new Node();
size = 0;
}
// 获得Trie中存储的单词数量
public int getSize(){
return size;
}
// 向Trie中添加一个新的单词word
public void add(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null) // 一个字符对应一个Node节点
cur.next.put(c, new Node());
cur = cur.next.get(c);
}
// 如果当前的node已经是一个word,则不需要添加
if(!cur.isWord){
cur.isWord = true;
size ++;
}
}
}
2、查询
Trie查找操作遍历带查找的字符串的字符,如果每个节点都存在,并且待查找字符串的最后一个字符对应的Node的 isWord 属性为 true ,则表示该单词存在
// 查询单词word是否在Trie中
public boolean contains(String word){
Node cur = root;
for(int i = 0 ; i < word.length() ; i ++){
char c = word.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return cur.isWord;
}
3、前缀查询
前缀查询和上面的查询操作基本类似,就是不需要判断 isWord 了
// 查询是否在Trie中有单词以prefix为前缀
public boolean isPrefix(String prefix){
Node cur = root;
for(int i = 0 ; i < prefix.length() ; i ++){
char c = prefix.charAt(i);
if(cur.next.get(c) == null)
return false;
cur = cur.next.get(c);
}
return true;
}
4、Trie字典树搜索和正则匹配
对应Leetcode 211题添加与搜索单词
参考模型
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return match(root, word, 0);
}
private boolean match(Node node, String word, int index){
if(index == word.length())
return node.isWord;
char c = word.charAt(index);
if(c != '.') {
if(node.next.get(c) == null)
return false;
return match(node.next.get(c), word, index + 1);
} else {
for(char nextChar: node.next.keySet()) {
if(match(node.next.get(nextChar), word, index + 1))
return true;
}
return false;
}
}