Simple Java solution beats 98%


  • 1
    Z

    The code is simple and self-explanatory:

    class TrieNode {
        // Initialize your data structure here.
        TrieNode children[];
        boolean isWord;
        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) {
            TrieNode cur = root;
            for (char ch : word.toCharArray()) {
                int index = ch - 'a';
                if (cur.children[index] == null) {
                    cur.children[index] = new TrieNode();
                }
                cur = cur.children[index];
            }
            cur.isWord = true;
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode destNode = findNodeInTrie(word);
            if (destNode == null) return false;
            return destNode.isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            return findNodeInTrie(prefix) != null;
        }
        
        private TrieNode findNodeInTrie(String word) {
            if (word == null) return null;
            TrieNode cur = root;
            for (char ch : word.toCharArray()) {
                int index = ch - 'a';
                if (cur.children[index] == null) return null;
                cur = cur.children[index];
            }
            return cur;
        }
    }
    

  • 0
    J

    nice solution and self explanatory.


Log in to reply
 

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