字典书Trie的实现

身为程序员,需要弄懂Trie(字典书的实现)
具体应用场景和讲解-请一定要看
提供的API如下

  • insert(String world) 向字典中插入
  • search(String world) 字典中查询此字符串
  • startWith(String world) 查询字典中的公有开头
class TrieNode {
    private TrieNode[] links;
    private final int R = 26;
    private boolean isEnd;
    private TrieNode root;
    public TrieNode(){
        this.links = new TrieNode();
    }
    public boolean containKeys(char c){
        return links[c-'a']!=null;
    }
    public void put(char c,TrieNode node){
        links[c-'a']=node;
    }
    public void setEnd(){
        this.isEnd = true;
    }
    public boolean isEnd(){
        return isEnd;
    }
    public TrieNode get(char c){
        return links[c-'a'];
    }
    public void insert(String world){
        TrieNode node = root;
        for (int i = 0; i < world.length(); i++) {
            char currentChar = world.charAt(i);
            if(!node.containKeys(currentChar)){
                node.put(currentChar, new TrieNode());
            }
            node = node.get(currentChar);
        }
        node.setEnd();
    }
    public boolean search(String world){
        TrieNode node = searchPrex(world);
        return node!=null && node.isEnd();
    }
    public boolean startWith(String world){
        TrieNode node = searchPrex(world);
        return node!=null;
    }
    public TrieNode searchPrex(String world){
        TrieNode node = root;
        for (int i = 0; i < world.length(); i++) {
            char currentChar = world.charAt(i);
            if(node.containKeys(c))node = node.get(currentChar);
            else return null;
        }
        return node;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容