Trie Implementation, leetcode 208

mail@pastecode.io avatar
unknown
java
7 months ago
1.7 kB
73
Indexable
Never
class Trie {
    class TrieNode {
        TrieNode[] children;
        boolean isEnd;

        public TrieNode() {
            this.children = new TrieNode[26];
            this.isEnd = false;
        }
    }

    TrieNode root;
    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode temp = root;

        for(int i=0; i<word.length(); i++){
            char ch = word.charAt(i);
            int idx = ch-'a';

            if(temp.children[idx] == null){
                temp.children[idx] = new TrieNode();
            }

            temp = temp.children[idx];
        }

        temp.isEnd = true;
    }
    
    public boolean search(String word) {
        TrieNode temp = root;

        for(int i=0; i<word.length(); i++){
            char ch = word.charAt(i);
            int idx = ch-'a';

            if(temp.children[idx] == null){
                return false;
            }

            temp = temp.children[idx];
        }

        // if(temp.isEnd == true){ // this is the end of the word
        //     return true;
        // }

        return temp.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode temp = root;

        for(int i=0; i<prefix.length(); i++){
            char ch = prefix.charAt(i);
            int idx = ch-'a';

            if(temp.children[idx] == null){
                return false;
            }

            temp = temp.children[idx];
        }

        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);
 */
Leave a Comment