Posts

Showing posts with the label Implement Trie

Implement Trie (Prefix Tree)

Implement a trie with insert , search , and startsWith methods. Example: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true Note: You may assume that all inputs are consist of lowercase letters a-z . All inputs are guaranteed to be non-empty strings.   class TrieNode {         private TrieNode[] nodeLinks;     public boolean isEnd;     public TrieNode() {         nodeLinks = new TrieNode[26];     }     public boolean containsKey(char ch) {         return nodeLinks[ch -'a'] != null;     }     public TrieNode get(char ch) {         return nodeLinks[ch -'a'];     }     public void put(char ch, TrieNode node) {         nodeLinks[ch -'a'] = node;     } } class Trie {     /** Initialize your data structure here. */