Clear Java solution (97%), easy to understand


  • 0
    class TrieNode {
        // Initialize your data structure here.
        public TrieNode() {
            children = new TrieNode[26];
            isWord = false;
        }
        
        TrieNode[] children;
        boolean isWord;
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            insert(word, 0, root);
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            if (word.length() == 0) return false;
            return search(word, 0, root);
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            if (prefix.length() == 0) return false;
            return startsWith(prefix, 0, root);
        }
        
        private void insert(String word, int index, TrieNode node) {
            if (node.children[word.charAt(index) - 'a'] == null) node.children[word.charAt(index) - 'a'] = new TrieNode();
            if (index == word.length() - 1) node.children[word.charAt(index) - 'a'].isWord = true;
            else insert(word, index + 1, node.children[word.charAt(index) - 'a']);
        }
        
        private boolean search(String word, int index, TrieNode node) {
            if (node.children[word.charAt(index) - 'a'] == null) return false;
            if (index == word.length() - 1) return node.children[word.charAt(index) - 'a'].isWord;
            return search(word, index + 1, node.children[word.charAt(index) - 'a']);
        }
        
        private boolean startsWith(String prefix, int index, TrieNode node) {
            if (index == prefix.length()) return true;
            if (node.children[prefix.charAt(index) - 'a'] == null) return false;
            return startsWith(prefix, index + 1, node.children[prefix.charAt(index) - 'a']);
        }
    }
    

Log in to reply
 

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