https://leetcode-cn.com/problems/implement-trie-prefix-tree/
思路:每个节点存储26个子节点——相当于从小写字母
a
a
a到
z
z
z,我们还需要知道当前节点是否是某个字符串的尾端,由于本题不需要计数,那么用一个
b
o
o
l
bool
bool值记录即可。
class Trie {
public:
/** Initialize your data structure here. */
Trie() {
child.resize(26,nullptr);
}
/** Inserts a word into the trie. */
void insert(const string& word) {
Trie *cur=this;
for(char ch:word)
{
ch-='a';
if(!cur->child[ch])
cur->child[ch]=new Trie();
cur=cur->child[ch];
}
cur->end=true;
}
/** Returns if the word is in the trie. */
bool search(const string& word) {
Trie *cur=this;
for(char ch:word)
{
ch-='a';
if(cur->child[ch])
cur=cur->child[ch];
else
return 0;
}
return cur->end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(const string& prefix) {
Trie *cur=this;
for(char ch:prefix)
{
ch-='a';
if(cur->child[ch])
cur=cur->child[ch];
else
return 0;
}
return 1;
}
private:
vector<Trie*> child;
bool end=false;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/