lintcode-medium-Implement Trie
Implement a trie with insert, search, and startsWith methods.
/** * Your Trie object will be instantiated and called as such: * Trie trie = new Trie(); * trie.insert("lintcode"); * trie.search("lint"); will return false * trie.startsWith("lint"); will return true */ class TrieNode { // Initialize your data structure here. char c; HashMap<Character, TrieNode> children; boolean isLeaf; public TrieNode() { this.children = new HashMap<Character, TrieNode>(); this.isLeaf = false; } public TrieNode(char c){ this.c = c; this.children = new HashMap<Character, TrieNode>(); this.isLeaf = false; } } public class Solution { private TrieNode root; public Solution() { root = new TrieNode(); } // Inserts a word into the trie. public void insert(String word) { if(word == null || word.length() == 0) return; TrieNode temp = root; for(int i = 0; i < word.length(); i++){ char c = word.charAt(i); if(temp.children.containsKey(c)){ temp = temp.children.get(c); } else{ temp.children.put(c, new TrieNode(c)); temp = temp.children.get(c); } if(i == word.length() - 1) temp.isLeaf = true; } return; } // Returns if the word is in the trie. public boolean search(String word) { if(word == null || word.length() == 0) return true; TrieNode temp = root; for(int i = 0; i < word.length(); i++){ char c = word.charAt(i); if(temp.children.containsKey(c)){ temp = temp.children.get(c); } else return false; } return temp.isLeaf; } // Returns if there is any word in the trie // that starts with the given prefix. public boolean startsWith(String prefix) { if(prefix == null || prefix.length() == 0) return true; TrieNode temp = root; for(int i = 0; i < prefix.length(); i++){ char c = prefix.charAt(i); if(temp.children.containsKey(c)){ temp = temp.children.get(c); } else return false; } return true; } }