Implement a trie with insert
, search
, and startsWith
methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
Solution:
1 class TrieNode { 2 TrieNode[] childs; 3 boolean hasWords; 4 5 // Initialize your data structure here. 6 public TrieNode() { 7 childs = new TrieNode[26]; 8 hasWords = false; 9 } 10 } 11 12 public class Trie { 13 private TrieNode root; 14 15 public Trie() { 16 root = new TrieNode(); 17 } 18 19 // Inserts a word into the trie. 20 public void insert(String word) { 21 TrieNode cur = root; 22 for (int i=0;i<word.length();i++){ 23 char curChar = word.charAt(i); 24 if (cur.childs[curChar-'a']==null){ 25 cur.childs[curChar-'a'] = new TrieNode(); 26 } 27 cur = cur.childs[curChar-'a']; 28 } 29 cur.hasWords = true; 30 } 31 32 // Returns if the word is in the trie. 33 public boolean search(String word) { 34 TrieNode cur = root; 35 for (int i=0;i<word.length();i++){ 36 char curChar = word.charAt(i); 37 if (cur.childs[curChar-'a']==null){ 38 return false; 39 } 40 cur = cur.childs[curChar-'a']; 41 } 42 return cur.hasWords; 43 } 44 45 // Returns if there is any word in the trie 46 // that starts with the given prefix. 47 public boolean startsWith(String prefix) { 48 TrieNode cur = root; 49 for (int i=0;i<prefix.length();i++){ 50 char curChar = prefix.charAt(i); 51 if (cur.childs[curChar-'a']==null){ 52 return false; 53 } 54 cur = cur.childs[curChar-'a']; 55 } 56 return true; 57 } 58 } 59 60 // Your Trie object will be instantiated and called as such: 61 // Trie trie = new Trie(); 62 // trie.insert("somestring"); 63 // trie.search("key");