[java/16ms] Neat code, Trie :-0


  • 0

    In order to get better performance, you can cache root.next[c - 'a']. Well, for readability...

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

Log in to reply
 

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