版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43126117/article/details/100660099
回想我们百度一下的过程,输入几个单词后,自动搜索出可能的选择,当没有完全匹配的搜索结果,可以返回前缀最相似的可能。 这个功能实现原理是上面呢?
这个功能的原理是字典树,通过匹配前缀,再通过一些内部算法,达到相似的可能,再输出给我们选择。
字典树 是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
leetcode:208实现 Trie (前缀树)
class Trie {
class TrieNode {
char value;
TrieNode[] childer;
Boolean isEng = false; //下面是否有节点
public TrieNode(char c) {
this.value = c;
childer = new TrieNode[26];//仅限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 p = root;
/* for (int i = 0; i < word.length(); i++) {
// if (p.childer[word.length() - 'a'] == word.charAt(i))
if (p.childer[word.charAt(i) - 'a'] == null) {
p.childer[word.charAt(i) - 'a'] = new TrieNode(word.charAt(i));
}
p = p.childer[word.charAt(i) - 'a'];
}*/
for (char c : word.toCharArray()) { //简写
if (p.childer[c - 'a'] == null) p.childer[c - 'a'] = new TrieNode(c);
p = p.childer[c - 'a'];
}
p.isEng = true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) { //搜索全部,即最后节点为Nil
TrieNode p = root;
for (char c : word.toCharArray()) {
if (p.childer[c - 'a'] == null) return false;
p = p.childer[c - 'a'];
}
/*for (int i = 0; i < word.length(); i++) {
if (p.childer[word.charAt(i) - 'a'] == null) return false;
p = p.childer[word.charAt(i) - 'a'];
}*/
return p.isEng;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) { //只要匹配即可以
TrieNode p = root;
for (char c : prefix.toCharArray()) {
if (p.childer[c - 'a'] == null) return false;
p = p.childer[c - 'a'];
}
return true;
}
}