这个就是字典树了,我用unordered_map时间上更节省一些。
class TrieNode {
public:
unordered_map<char,TrieNode *> children;
bool isLeaf;
TrieNode(){isLeaf = false;};
};
class Trie {
public:
TrieNode *root;
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode *cur = root;
for (int i = 0;i<word.size();i++) {
if(cur->children.find(word[i]) == cur->children.end()) {
cur->children[word[i]] = new TrieNode();
}
cur = cur->children[word[i]];
}
cur->isLeaf = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode *cur = root;
for (int i = 0;i<word.size();i++) {
if(cur->children.find(word[i]) == cur->children.end()) {
return false;
}
cur = cur->children[word[i]];
}
if(cur->isLeaf) return true;
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *cur = root;
for (int i = 0;i<prefix.size();i++) {
if(cur->children.find(prefix[i]) == cur->children.end()) {
return false;
}
cur = cur->children[prefix[i]];
}
return true;
}
};