查找字符串是否存在,比如查找某个工会名字是否存在,查找某个人名是否存在,但是删除的话比较麻烦,因为可能删掉前缀相同但是别人的名字(类似redis的布隆过滤器,猜测是否命中,但是不一定就有)
Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
请你实现 Trie 类:
输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]
解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 True
trie.search("app"); // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app"); // 返回 True
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/implement-trie-prefix-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* 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);
*/
class Trie {
private:
vector<Trie*> _child;
bool _isEnd;
Trie* _getNode(string word)
{
Trie* tr = this;
for(auto&s:word)
{
if(!tr->_child[s-'a'])
return nullptr;
tr = tr->_child[s - 'a'];
}
return tr;
}
public:
Trie()
:_child(26), _isEnd(false)
{
}
//
void insert(string word)
{
Trie* tr = this;
for(auto& n:word)
{
if(tr->_child[n-'a'] == nullptr)
tr->_child[n-'a'] = new Trie();
tr = tr->_child[n-'a'];
}
tr->_isEnd = true;
}
//搜索
bool search(string word)
{
Trie* node = _getNode(word);
return node && node->_isEnd;
}
//前序匹配
bool startsWith(string prefix)
{
return _getNode(prefix) != nullptr;
}
};
分配的内存的时候存在数组里面,但是如果这段数据是放在共享内存的话,不该放在std容器里面,因为这个进程一但宕机,从共享内存恢复的话,std::vector的容器会失效,幸运的话会指向乱码的区域,糟糕的话会再宕机一次