My concise Java solution.


  • 0
    J

    I think it should be self-explained already.

    class TrieNode {
        public char val;
        public boolean isWord;
        public TrieNode[] next;
        
        // Initialize your data structure here.
        public TrieNode(char val) {
            next = new TrieNode[26];
            this.val = val;
            this.isWord = 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;
            char[] wordArray = word.toCharArray();
            for (int depth = 0; depth < wordArray.length; depth++) {
                TrieNode tmp = node.next[wordArray[depth] - 'a'];
                if (tmp == null) {
                    tmp = new TrieNode(wordArray[depth]);
                    node.next[wordArray[depth] - 'a'] = tmp;
                }
                if (depth == wordArray.length - 1) { // Setup the isWord flag
                    tmp.isWord = true;
                }
                
                node = tmp;
            }
        }
    
        // Returns if the word is in the trie.
        public boolean search(String word) {
            TrieNode node = findLastNode(word.toCharArray());
            return (node != null && node.isWord) ? true : false;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        public boolean startsWith(String prefix) {
            return (findLastNode(prefix.toCharArray()) != null) ? true : false;
        }
        
        // Find the last node which holds the last character 
        // of the given string.
        private TrieNode findLastNode(char[] str) {
            TrieNode node = root;
            for (int depth = 0; depth < str.length; depth++) {
                node = node.next[str[depth] - 'a'];
                if (node == null) return null;
            }
            return node;
        }
    }
    
    // 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.