题目
代码(首学前缀树)
class Trie {
private:
vector<Trie*> children;
bool isEnd;
Trie* searchPrefix(string prefix) {
Trie* node = this;
for(char c : prefix) {
c -= 'a';
if(node->children[c] == nullptr) {
return nullptr;
}
node = node->children[c];
}
return node;
}
public:
Trie() : children(26), isEnd(false) {}
void insert(string word) {
Trie* node = this;
for(char c : word) {
c -= 'a';
if(node->children[c] == nullptr) {
node->children[c] = new Trie;
}
node = node->children[c];
}
node->isEnd = true;
}
bool search(string word) {
Trie* node = searchPrefix(word);
return node && node->isEnd;
}
bool startsWith(string prefix) {
return searchPrefix(prefix);
}
};
代码(9.23 二刷看解析)
进一步熟悉前缀树
class Trie {
private:
vector<Trie*> children;
bool isEnd;
Trie* searchPrefix(string prefix) {
Trie* node = this;
for(char c : prefix) {
c -= 'a';
if(node->children[c] == nullptr) {
return nullptr;
}
node = node->children[c];
}
return node;
}
public:
Trie() : children(26), isEnd(false){}
void insert(string word) {
Trie* node = this;
for(char c : word) {
c -= 'a';
if(node->children[c] == nullptr) {
node->children[c] = new Trie;
}
node = node->children[c];
}
node->isEnd = true;
}
bool search(string word) {
auto node = searchPrefix(word);
return node && node->isEnd;
}
bool startsWith(string prefix) {
return searchPrefix(prefix);
}
};