208. 实现 Trie (前缀树)
作者:互联网
首先,我看见这种偏数据结构题自动带一点恐惧,这次还是不会写
这是一个树,每个结点有26个子结点,前缀不存在则为空,然后标记结束位置
使用vector+指针创造树
然后就是构造函数,vector调用自己的构造函数,差点看懵了
Trie():children(26),isEnd(false){}
查看代码
class Trie {
private:
vector<Trie*> children;
bool isEnd;
public:
/** Initialize your data structure here. */
Trie():children(26),isEnd(false){} //这份代码的局限性在于你得知道单词的字符范围
/** Inserts a word into the trie. */
void insert(string word) {
Trie *nownode = this;
for (char ch : word)
{
ch -= 'a'; //字符跟下标对应
if(nownode->children[ch] == nullptr)
nownode->children[ch] = new Trie();
nownode = nownode->children[ch];
}
nownode->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie * nownode = this;
for (char ch : word)
{
ch -= 'a';
if(nownode->children[ch] == nullptr)
return false;
nownode = nownode->children[ch];
}
return nownode->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie *nownode = this;
for (char ch : prefix)
{
ch -= 'a';
if(nownode->children[ch] == nullptr)
return false;
nownode = nownode->children[ch];
}
return true;
}
};
标签:ch,word,前缀,Trie,208,isEnd,nownode,children 来源: https://www.cnblogs.com/jozon/p/15708651.html