Java solution (easy to understand)


  • 0
    D
    public class Trie {
        
        private TrieNode root;
        
        public class TrieNode{
            TrieNode[] arr;
            boolean isEnd;
            public TrieNode() {
                this.arr = new TrieNode[26];
            }
        }
        
    
        /** Initialize your data structure here. */
        public Trie() {
            root = new TrieNode();
        }
        
        /** Inserts a word into the trie. */
        public void insert(String word) {
            TrieNode p = root;
            for (int i = 0; i < word.length(); i++) {
                int index = word.charAt(i) - 'a';
                if (p.arr[index] == null) {
                    TrieNode temp = new TrieNode();
                    p.arr[index] = temp;
                    p = temp;
                }
                else {
                    p = p.arr[index];
                }
            }
            p.isEnd = true;
        }
        
        /** Returns if the word is in the trie. */
        public boolean search(String word) {
            TrieNode p = root;
            for (int i = 0; i < word.length(); i++) {
                int index = word.charAt(i) - 'a';
                if (p.arr[index] == null) return false;
                p = p.arr[index];
            }
            return p != null && p.isEnd;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        public boolean startsWith(String prefix) {
            TrieNode p = root;
            for (int i = 0; i < prefix.length(); i++) {
                int index = prefix.charAt(i) - 'a';
                if (p.arr[index] == null) return false;
                p = p.arr[index];
            }
            return true;
        }
    }

Log in to reply
 

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