前缀树

145 阅读1分钟

须知

  • 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
  • 我们可以知道前缀树其实是一棵特殊的多叉树
  • 一般的多叉树我们如下定义
class TreeNode{
    int val;
    TreeNode[] children;
}
  • 结合前缀树所完成的功能,其实我们不用显示定义val,结合多叉树的定义即可写出前缀树的定义

image.png

class Trie {
    //当前节点是否末端节点
    private boolean isEnd;
    private Trie[] children;
    
    public Trie() {
        isEnd=false;
        children=new Trie[26];
    }
    //添加单词
    public void insert(String word) {
        Trie trie=this;
        for(char c:word.toCharArray()){
            if(trie.children[c-'a']==null){
                trie.children[c-'a']=new Trie();
            }
            trie=trie.children[c-'a'];
        }
        trie.isEnd=true;
    }
    //查询某个单词是否在树中
    public boolean search(String word) {
        Trie trie=this;
        for(char c:word.toCharArray()){
            if(trie.children[c-'a']==null){
                return false;
            }
            trie=trie.children[c-'a'];
        }
        return trie.isEnd;
    }
    //查询某个前缀是否在树中
    public boolean startsWith(String prefix) {
        Trie trie=this;
        for(char c:prefix.toCharArray()){
            if(trie.children[c-'a']==null){
                return false;
            }
            trie=trie.children[c-'a'];
        }
        return true;
    }
}