题目:

思路:
tire树,学过,模板题。一种数据结构与算法的结合吧。

代码是:
//code
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
Trie() {
isEnd = false;
memset(next, 0, sizeof(next));
}
void insert(string word) {
Trie* node = this;
for (char c : word) {
if (node->next[c-'a'] == NULL) {
node->next[c-'a'] = new Trie();
}
node = node->next[c-'a'];
}
node->isEnd = true;
}
bool search(string word) {
Trie* node = this;
for (char c : word) {
node = node->next[c - 'a'];
if (node == NULL) {
return false;
}
}
return node->isEnd;
}
bool startsWith(string prefix) {
Trie* node = this;
for (char c : prefix) {
node = node->next[c-'a'];
if (node == NULL) {
return false;
}
}
return true;
}
};
文章介绍了Trie树(字典树),一种用于高效存储和检索字符串的数据结构。通过示例代码展示了如何使用C++实现Trie树的插入、搜索和检查字符串是否以特定前缀开始的功能。
572

被折叠的 条评论
为什么被折叠?



