Clean recursive 19ms Java solution


  • 0
    S
    class TrieNode {
        // Initialize your data structure here.
        boolean isWord;
        TrieNode[] next;
        public TrieNode() {
            isWord = 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 node, String word, int d){
            if(node == null) node = new TrieNode();
            if(d == word.length()){
                node.isWord = true;
                return node;
            }
            char c = word.charAt(d);
            node.next[c-'a'] = insert(node.next[c-'a'], word, d+1);
            return node;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            if(word == null || word.length()==0) return false;
            return search(root, word, 0);
        }
        
        private boolean search(TrieNode node, String word, int d){
            if(node == null) return false;
            if(d == word.length()){
                return node.isWord;
            }
            char c = word.charAt(d);
            return search(node.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) {
            if(prefix == null || prefix.length()==0) return false;
            return startsWith(root, prefix, 0);
        }
        
        private boolean startsWith(TrieNode node, String prefix, int d){
            if(node == null) return false;
            if(d == prefix.length()){
                return true;
            }
            char c = prefix.charAt(d);
            return startsWith(node.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.