LeetCode 208.Implement Trie (Prefix Tree)【Java】

Title description

Implement Trie (Prefix Tree)

AC code

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);
 */
Published 201 original articles · Like9 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/weixin_40992982/article/details/105516612
Recommended