LeetCode 208.Implement Trie (Árbol de prefijos) 【Java】

Descripción del título

Implementar Trie (árbol de prefijos)

Código AC

class Trie {
    class Node{
        boolean is_end;
        Node[] son=new Node[26];
    }
    Node root;
    /** Initialize your data structure here. */
    public Trie() {
        root=new Node();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Node p=root;
        char[] ch=word.toCharArray();
        for(char item:ch){
            int k=item-'a';
            if(p.son[k]==null) 
                p.son[k]=new Node();
            p=p.son[k];
        }
        p.is_end=true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        Node p=root;
        char[] ch=word.toCharArray();
        for(char item:ch){
            int k=item-'a';
            if(p.son[k]==null) return false;
            p=p.son[k];
        }
        return p.is_end;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Node p=root;
        char[] ch=prefix.toCharArray();
        for(char item:ch){
            int k=item-'a';
            if(p.son[k]==null) return false;
            p=p.son[k];
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */
201 artículos originales publicados · Me gusta9 · Visitantes más de 10,000

Supongo que te gusta

Origin blog.csdn.net/weixin_40992982/article/details/105516612
Recomendado
Clasificación