字典书Trie的实现

作者: 奔跑的蛙牛 | 来源:发表于2019-03-20 20:28 被阅读0次

身为程序员,需要弄懂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;
    }
}

相关文章

网友评论

    本文标题:字典书Trie的实现

    本文链接:https://www.haomeiwen.com/subject/mffxvqtx.html