class TrieNode {
private final int R = 26;
private TrieNode[] links;
private boolean isEnd;
public TrieNode() {
links = new TrieNode[R];
}
public boolean containsKey(char ch) {
return links[ch - 'a'] != null;
}
public TrieNode get(char ch) {
return links[ch - 'a'];
}
public void put(char ch, TrieNode node) {
links[ch - 'a'] = node;
}
public void setEnd() {
isEnd = true;
}
public boolean isEnd() {
return isEnd;
}
}
class Trie {
public TrieNode root;
/**
* Initialize your data structure here.
*/
public Trie() {
root = new TrieNode();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!node.containsKey(ch)) {
node.put(ch, new TrieNode());
}
node = node.get(ch);
}
node.setEnd();
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
TrieNode node = searchPrefix(word);
return node != null && node.isEnd();
}
private TrieNode searchPrefix(String word) {
TrieNode 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;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
TrieNode node = searchPrefix(prefix);
return node != null;
}
}
字典树(Trie)数,又称单词查找树或键数,典型应用是用于统计和排序大量的字符串,经常被搜索引擎用于文本词频统计。
优点:最大限度地减少无谓的字符串比较,查询效率比哈希表高
Trie数实现如下
二叉搜索树(有序二叉树、排序二叉树)
以此类推:左、右子区为分别为二叉查找树
AVL树(平衡二叉树)
缺点:节点需要存储额外信息、且调整次数频繁
红黑树(近似平衡的二叉搜索树)
能确保任何一个结点的左右子树的高度差小于两倍