特别要注意一定要用指针,否则会导致无法存储下一个。
struct Node {
bool isWord;
//还是得用指针
map<char, Node*> next;
Node(bool _isWord):isWord(_isWord){}
Node():isWord(false){}
};
class Trie {
private:
Node* root;
int size;
public:
Trie() {
root = new Node();
size = 0;
}
void insert(string word) {
Node* cur = root;
for (auto& ch : word) {
if (cur->next.count(ch) == 0) {
//cur.next.insert({ch, Node()});
cur->next[ch] = new Node();
}
cur = cur->next[ch];
}
if (cur->isWord == false) {
cur->isWord = true;
size++;
}
}
bool search(string word) {
Node* cur = root;
for (auto& ch : word) {
if (cur->next.count(ch) == 0) {
return false;
}
cur = cur->next[ch];
}
return cur->isWord;
}
bool startsWith(string prefix) {
Node* cur = root;
for (auto& ch : prefix) {
if (cur->next.count(ch) == 0) {
return false;
}
cur = cur->next[ch];
}
return true;
}
};