Java Solution Uses Additional Method to simplify code


  • 0

    Uses searchNode method to simplify the code for search and startsWith

    class TrieNode {
        public char val;
        public TrieNode children[];
        boolean hasWord;
        
        // Initialize your data structure here.
        public TrieNode() {
            this.children = new TrieNode[26];
            hasWord = false;
        }
        public TrieNode(char val) {
            this.val = val;
            this.children = new TrieNode[26];
            hasWord = false;
        }
    }
    
    public class Trie {
        private TrieNode root;
    
        public Trie() {
            root = new TrieNode(' ');
        }
    
        // Inserts a word into the trie.
        public void insert(String word) {
            TrieNode node = root;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                if (node.children[c - 'a'] == null) {
                    node.children[c - 'a'] = new TrieNode(c);
                }
                node = node.children[c - 'a'];
            }
            node.hasWord = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode node = searchNode(word);
            if (node == null) {
                return false;
            }
            return node.hasWord;
        }
        
        // Search for a node with a prefix
        private TrieNode searchNode(String prefix) {
            TrieNode node = root;
            for (int i = 0; i < prefix.length(); i++) {
                char c = prefix.charAt(i);
                if (node.children[c - 'a'] == null) {
                    return null;
                }
                node = node.children[c - 'a'];
            }
            return node;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            return searchNode(prefix) != null;
        }
    }
    

Log in to reply
 

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