/** Initialize your data structure here. */ publicTrie(){ root = new TrieNode(); } /** Inserts a word into the trie. */ publicvoidinsert(String word){ TrieNode node = root; for(int i=0; i<word.length(); i++){ char c = word.charAt(i); if(!node.containsKey(c)){ node.set(c, new TrieNode()); } node = node.get(c); } node.setEnd(); } private TrieNode searchPrefix(String word){ TrieNode node = root; for(int i=0; i<word.length(); i++){ char c = word.charAt(i); if(node.containsKey(c)) node = node.get(c); 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){ TrieNode node = searchPrefix(prefix); return node!=null; } }
/** * Your Trie object will be instantiated and called as such: * Trie obj = new Trie(); * obj.insert(word); * boolean param_2 = obj.search(word); * boolean param_3 = obj.startsWith(prefix); */