Easy Understanding and Concise Java Solution


  • 0
    X

    The main idea is implementing an R-way Trie. Use a Node array to keep the children node, and use their character as index.

    class TrieNode {
        public boolean hit;
        public TrieNode[] next;
        public TrieNode() {
            hit = false;
            next = new TrieNode[26];
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            root = insert(root, word, 0);
        }
    
        private TrieNode insert(TrieNode x, String word, int d){
            if(x == null) x = new TrieNode();
            if(d == word.length()){
                x.hit = true;
                return x;
            }
            char c = word.charAt(d);
            x.next[c - 'a'] = insert(x.next[c - 'a'], word, d + 1);
            return x;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode temp = search(root, word, 0);
            if(temp == null) return false;
            return temp.hit;
        }
    
        private TrieNode search(TrieNode x, String word, int d){
            if(x == null) return null;
            if(d == word.length()) return x;
            char c = word.charAt(d);
            return search(x.next[c - 'a'], word, d + 1);
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            TrieNode temp = startsWith(root, prefix, 0);
            if(temp == null) return false;
            return true;
        }
    
        private TrieNode startsWith(TrieNode x, String prefix, int d){
            if(x == null) return null;
            if(d == prefix.length()) return x;
            char c = prefix.charAt(d);
            return startsWith(x.next[c - 'a'], prefix, d + 1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.