class TrieNode {
// Initialize your data structure here.public HashMap<Character,TrieNode> map;
public boolean flag = false;
publicTrieNode() {
map = new HashMap<Character,TrieNode>();
}
}
publicclass Trie {
private TrieNode root;
publicTrie() {
root = new TrieNode();
}
// Inserts a word into the trie.publicvoidinsert(String word) {
TrieNode node = root;
int index = 0;
while (index < word.length() && node.map.containsKey(word.charAt(index))) {
node = node.map.get(word.charAt(index));
index++;
}
while (index < word.length()) {
node.map.put(word.charAt(index), new TrieNode());
node = node.map.get(word.charAt(index));
index++;
}
node.flag = true;
}
// Returns if the word is in the trie.public boolean search(String word) {
TrieNode node = root;
for (int i = 0; i < word.length(); i++) {
char tmp = word.charAt(i);
if (!node.map.containsKey(tmp)) returnfalse;
node = node.map.get(word.charAt(i));
}
return node.flag;
}
// Returns if there is any word in the trie// that starts with the given prefix.public boolean startsWith(String prefix) {
TrieNode node = root;
for (int i = 0; i < prefix.length(); i++) {
char tmp = prefix.charAt(i);
if (!node.map.containsKey(tmp)) returnfalse;
node = node.map.get(prefix.charAt(i));
}
returntrue;
}
}
LeetCode 208: Implement Trie (Prefix Tree)思路使用HashMap存储后代,节省空间;需要设定一个boolean值来表示是否该节点为一个单词的结束;代码class TrieNode { // Initialize your data structure here. public HashMap<Character,TrieNode> ma