应用场景
在搜索引擎中搜索关键字的提示功能。
这个是如何进行实现的勒?当然这里讲的还是最基础的啦,他就是Trie树——字典树
字典树
功能:是一种专门处理字符串匹配的数据结构,用来解决一组字符串集合中快速查找某个字符串的问题
本质:利用字符串之间的公共前缀,将重复的前缀合并在一起
比如说对于hero, high , hit 三个字符串其字典树形状为:
重复利用单词的公共前缀。
字典树的基本结构及操作
一、基本数据结构及节点的基本操作
class TrieNode{
TrieNode[] links; //当前层的link存储下一层的引用的数组
final int R = 26; //因为每一个位置最多只能时26个英文字母
boolean isEnd; //当前字母是否可以为单词的末尾
public TrieNode() {
links = new TrieNode[R];
}
public boolean containsKey(char ch){//判断该节点的下一位是否含有ch节点
return links[ch - 'a'] != null;
}
public TrieNode get(char ch){ //判断含有该节点后,就跳到下一个位在进行判断
return links[ch - 'a'];
}
public void setIsEnd(){//该节点可以是单词的末尾
isEnd = true;
}
public boolean isEnd(){
return isEnd;
}
}
然后主类进行存储根节点即可;
在java中,节点类一般以内部类的形式进行表达。
二、字典树的操作
上面写的是单个节点应该有的数据结构及操作,我们再来看看整颗树应该具有那些操作
字典树的主要操作两个:
1. 插入单词
2. 查看单词是否在字典树中
public class Trie {
private TrieNode root; //保存根节点的位置
public Trie() {
root = new TrieNode();
}
//进行插入单词
public void insert(String word) {
TrieNode node = root;
char[] chars = word.toCharArray();
for (char ch : chars) {
if (!node.containsKey(ch))
node.put(ch, new TrieNode());
node = node.get(ch);
}
node.setEnd();
}
//进行单词的查询
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd();
}
//进行前缀的查询
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
//因为查询前缀和单词查询都有用到因此就单独写出来
private TrieNode searchPrefix(String word) {
TrieNode node = root;
char[] chars = word.toCharArray();
for (char ch : chars) {
if (!node.containsKey(ch))
return null;
node = node.get(ch);
}
return node;
}
}
然后大家在看了之后可以去leetcode练习一下
208. 实现 Trie (前缀树) leetcode