/** * Initialize your data structure here. */ publicTrie() { root = newTrieNode(); }
/** * Inserts a word into the trie. */ publicvoidinsert(String word) { TrieNodenode= root; for (inti=0; i < word.length(); i++) { charcur= word.charAt(i); if (!node.containsKey(cur)) { node.put(cur, newTrieNode()); } node = node.get(cur); } node.setEnd(); }
/** * Returns if the word is in the trie. */ publicbooleansearch(String word) { TrieNodenode= searchPrefix(word); return node != null && node.isEnd(); }
/** * Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix) { return searchPrefix(prefix) != null; }
private TrieNode searchPrefix(String word) { TrieNodenode= root; for (inti=0; i < word.length(); i++) { charcur= word.charAt(i); if (!node.containsKey(cur)) { returnnull; } node = node.get(cur); } return node; } }