/** * Initialize the data structure. */ publicTrie(){ // 修改处 root = new ArrayTrieNode(); // root = new HashMapTrieNode(); }
/** * Inserts a word into the trie. */ publicvoidinsert(String word){ Node node = root; for (int i = 0; i < word.length(); i++) { char curLetter = word.charAt(i); if (node.notContainsKey(curLetter)) { node.put(curLetter); } node = node.get(curLetter); } node.setEndingChar(); }
/** * search a prefix or whole key in trie and returns the node where search ends */ private Node searchPrefix(String word){ Node node = root; for (int i = 0; i < word.length(); i++) { char curLetter = word.charAt(i); if (node.notContainsKey(curLetter)) { returnnull; } node = node.get(curLetter); } return node; }
/** * Returns if the word is in the trie. */ publicbooleansearch(String word){ Node node = searchPrefix(word); return node != null && node.isEndingChar(); }
/** * Returns if there is any word in the trie that starts with the given prefix. */ publicbooleanstartsWith(String prefix){ Node node = searchPrefix(prefix); return node != null; } }