Easy solution beats 85% run time


  • 0
    S
    class TrieNode {
        // Initialize your data structure here.
        TrieNode[] children;
        boolean isLeaf;
        public TrieNode() {
            children = 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) {
            if(word == null) {
                return;
            }
    
            TrieNode cur = root;
            for(int i = 0; i < word.length(); i++) {
                int index = word.charAt(i)-'a';
                if(cur.children[index] == null) {
                    cur.children[index] = new TrieNode();
                }
                cur = cur.children[index];
            }
    
            cur.isLeaf = true;
        }
    
        public TrieNode searchNode(String word) {
            if(word == null) {
                return null;
            }
            TrieNode cur = root;
            for(int i = 0; i< word.length(); i++) {
                int index = word.charAt(i)-'a';
                if(cur.children[index] == null) {
                    return null;
                }
                cur = cur.children[index];
            }
            
            return cur;
        }
        
        // Returns if the word is in the trie.
        public boolean search(String word) {
            if(word == null) {
                return false;
            }
            TrieNode lastNode = searchNode(word);
            return  lastNode!=null && lastNode.isLeaf;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            if(prefix == null) {
                return false;
            }
            return searchNode(prefix)!=null;
        }
    }
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie = new Trie();
    // trie.insert("somestring");
    // trie.search("key");

Log in to reply
 

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