数据结构和算法后端小树林

字典书Trie的实现

2019-03-20  本文已影响0人  奔跑的蛙牛

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

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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读