|
| 1 | +package medium; |
| 2 | + |
| 3 | +public class ImplementTrie { |
| 4 | + class TrieNode { |
| 5 | + |
| 6 | + char val; |
| 7 | + boolean isWord; |
| 8 | + TrieNode[] children = new TrieNode[26]; |
| 9 | + |
| 10 | + // Initialize your data structure here. |
| 11 | + public TrieNode() {} |
| 12 | + |
| 13 | + public TrieNode(char c) { |
| 14 | + this.val = c; |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + public class Trie { |
| 19 | + private TrieNode root; |
| 20 | + |
| 21 | + public Trie() { |
| 22 | + root = new TrieNode(); |
| 23 | + root.val = ' ';//initialize root to be an empty char, this is a common practice as how Wiki defines Trie data structure as well |
| 24 | + } |
| 25 | + |
| 26 | + // Inserts a word into the trie. |
| 27 | + public void insert(String word) { |
| 28 | + TrieNode node = root; |
| 29 | + for(int i = 0; i < word.length(); i++){ |
| 30 | + if(node.children[word.charAt(i) - 'a'] == null){ |
| 31 | + node.children[word.charAt(i) - 'a'] = new TrieNode(word.charAt(i)); |
| 32 | + } |
| 33 | + node = node.children[word.charAt(i) - 'a']; |
| 34 | + } |
| 35 | + node.isWord = true; |
| 36 | + } |
| 37 | + |
| 38 | + // Returns if the word is in the trie. |
| 39 | + public boolean search(String word) { |
| 40 | + TrieNode node = root; |
| 41 | + for(int i = 0; i < word.length(); i++){ |
| 42 | + if(node.children[word.charAt(i) - 'a'] == null) return false; |
| 43 | + node = node.children[word.charAt(i) - 'a']; |
| 44 | + } |
| 45 | + return node.isWord; |
| 46 | + } |
| 47 | + |
| 48 | + // Returns if there is any word in the trie |
| 49 | + // that starts with the given prefix. |
| 50 | + public boolean startsWith(String prefix) { |
| 51 | + TrieNode node = root; |
| 52 | + for(int i = 0; i < prefix.length(); i++){ |
| 53 | + if(node.children[prefix.charAt(i) - 'a'] == null) return false; |
| 54 | + node = node.children[prefix.charAt(i) - '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"); |
| 64 | +} |
0 commit comments