/** Initialize your data structure here. */ publicTrie(){ root = new TrieNode(); }
/** Inserts a word into the trie. */ publicvoidinsert(String word){ TrieNode node = root; for (char ch : word.toCharArray()) { if (!node.containsKey(ch)) { node.put(ch, new TrieNode()); } node = node.get(ch); } node.setEnd(); }
/** search a prefix or whole key in trie and */ /** returns the node where search ends */ private TrieNode searchPrefix(String prefix){ TrieNode node = root; for (char ch : prefix.toCharArray()) { if (node.containsKey(ch)) { node = node.get(ch); } else { returnnull; } } return node; }
/** Returns if the word is in the trie. */ publicbooleansearch(String word){ TrieNode node = 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; } }