题目:题目链接
Trie又称字典树,前缀树。具体性质可以参照英文官方题解,里面还有Trie的用法,可以去看看还是挺有意思的。
其实坦白来说就是建树,每棵树都有最多26个结点也就是26个英文字母,我的代码是按照中文官方题解写的,顺便加了点自己的理解。看代码吧:
class Trie {
private:
vector<Trie*> children;//这是他的儿子,也是一棵Trie树
bool isEnd;//该结点是否是叶子结点
Trie* searchPrefix(string prefix) {
Trie* node = this;//this指针这里可以理解为根结点
for (char ch : prefix) {
ch -= 'a';
if (node->children[ch] == nullptr) return nullptr;//没有就别找了
node = node->children[ch];//接着找下一个字符
}
return node;//全部找完了,就返回叶子结点
}
public:
Trie() : children(26), isEnd(false) {}
void insert(string word) {//Inserts the string word into the trie.
Trie* node = this;
for (char ch : word) {
ch -= 'a';
if (node->children[ch] == nullptr) {//没有这个结点就创一个
node->children[ch] = new Trie();
}
node = node->children[ch];
}
node->isEnd = true;//表示叶子结点,也就是说word已经在这棵树里面了
}
bool search(string word) {//Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
Trie* node = this->searchPrefix(word);
return node != nullptr && node->isEnd;
}
bool startsWith(string prefix) {//Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
return this->searchPrefix(prefix) != nullptr;
}
};
/**
* 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);
*/
学习到了this指针的用法。
加油加油加油加油!!!