Trie (prefix tree) 实现 (C++)
来源:互联网 发布:山东师范大学网络教育 编辑:程序博客网 时间:2024/04/28 14:01
Trie有一个很有趣的用途,那就是自动提示。而且,前不久在一次面试里,也需要用Trie来解答。所以,在此对这个数据结构进行总结。
Trie,又称单词查找树或键树,是一种树形结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。
它有3个基本性质:
- 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
- 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
- 每个节点的所有子节点包含的字符都不相同。
有了这样一种数据结构,我们可以用它来保存一个字典,要查询改字典里是否有相应的词,是否非常的方便呢?我们也可以做智能提示,我们把用户已经搜索的词存在Trie里,每当用户输入一个词的时候,我们可以自动提示,比如当用户输入 ba, 我们会自动提示 bat 和 baii.
现在来讨论Trie的实现。
首先,我们定义一个Abstract Trie,Trie 里存放的是一个Node。这个类里有三个操作,一个是插入,一个是查询,另一个是startwiths(包含前缀)。具体实现放在后面。
class TrieNode {
public:char content; // the character included
bool isend; // if the node is the end of a word
int shared; // the number of the node shared ,convenient to implement delete(string key)
vector<TrieNode*> children; // the children of the node
// Initialize your data structure here.
TrieNode():content(' '), isend(false), shared(0) {}
TrieNode(char ch):content(ch), isend(false), shared(0) {}
TrieNode* subNode(char ch) {
if (!children.empty()) {
for (auto child : children) {
if (child->content == ch)
return child; }
}
returnnullptr; }
~TrieNode() {
for (auto child : children)
delete child; }
};
class Trie {
public: Trie() {
root =new TrieNode();
}// Inserts a word into the trie.
void insert(string s) {
if (search(s)) return;
TrieNode* curr = root;
for (auto ch : s) {
TrieNode* child = curr->subNode(ch);
if (child != nullptr) {
curr = child;
}
else {
TrieNode *newNode =new TrieNode(ch);
curr->children.push_back(newNode);
curr = newNode;
}
++curr->shared;
}
curr->isend = true; } // Returns if the word is in the trie.bool search(string key) {
TrieNode* curr = root;
for (auto ch : key) {
curr = curr->subNode(ch);
if (curr == nullptr)
returnfalse;
}
return curr->isend == true;
}
// Returns if there is any word in the trie// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* curr = root;
for (auto ch : prefix) {
curr = curr->subNode(ch);
if (curr == nullptr)
returnfalse;
}
returntrue;
}
~Trie() {
delete root;
}
private: TrieNode* root;
};
- Trie (prefix tree) 实现 (C++)
- Trie (prefix tree) 实现 (Java)
- Trie (prefix tree) 实现 (Java)
- LeetCode-Implement Trie (Prefix Tree) (C++)
- Trie Tree(Prefix Tree)
- leetcode208 Implement Trie (Prefix Tree)--java实现
- CareerCup Trie Prefix Tree
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- Implement Trie (Prefix Tree)
- 黑马程序员_92_反射
- return与exit的区别是什么?
- 二分查找算法
- 天津条形码 博客 正式开通,欢迎各位共同交流探讨!
- XAMPP在Ubuntu下详细的安装与启动步骤
- Trie (prefix tree) 实现 (C++)
- openssl编程
- Android 删除SD卡一个指定文件夹和其下的所有文件
- x86寄存器和栈帧
- P124.46
- activeMq从0开始
- 基金
- java设计模式(七)---代理模式
- 做一个“合格”的程序员