A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
class Trie {
static class node{
node[] child = new node[26];
boolean is_word = false; //截止这个结点是否是终止单词
}
node root;
public Trie() {
root = new node();
}
public void insert(String word) {
node cur = root;
for(int i = 0;i<word.length();i++)
{
char ch = word.charAt(i);
if(cur.child[ch - 'a']==null)
{
cur.child[ch - 'a'] = new node();
}
cur = cur.child[ch - 'a'];
}
cur.is_word = true;
}
public boolean search(String word) {
node cur = root;
int i;
for(i = 0;i<word.length() && cur.child[word.charAt(i) - 'a']!=null ;i++)
{
cur = cur.child[word.charAt(i) - 'a'];
}
return i == word.length() && cur.is_word;
}
public boolean startsWith(String prefix) {
node cur = root;
int i;
for(i = 0;i<prefix.length() && cur.child[prefix.charAt(i) - 'a']!=null ;i++)
{
cur = cur.child[prefix.charAt(i) - 'a'];
}
return i == prefix.length();
}
}
DELETION:
- 没有找到则直接返回
- 则最终找到的结点其标志位为真,将其置为假
- 如果该结点无孩子,则将其删除
- 如果有孩子意味着还有其余的单词以截止这个结点的单词(即欲删除的单词)为前缀