Trie (prefix tree) 实现 (C++)

来源:互联网 发布:山东师范大学网络教育 编辑:程序博客网 时间:2024/04/28 14:01

Trie有一个很有趣的用途,那就是自动提示。而且,前不久在一次面试里,也需要用Trie来解答。所以,在此对这个数据结构进行总结。

Trie,又称单词查找树键树,是一种形结构。典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

它有3个基本性质:

  1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  3. 每个节点的所有子节点包含的字符都不相同。

下面这个图就是Trie的表示,每一条边表示一个字符,如果结束,就用星号表示。在这个Trie结构里,我们有下面字符串,比如do, dork, dorm等,但是Trie里没有ba, 也没有sen,因为在a, 和n结尾,没有结束符号(星号)。



有了这样一种数据结构,我们可以用它来保存一个字典,要查询改字典里是否有相应的词,是否非常的方便呢?我们也可以做智能提示,我们把用户已经搜索的词存在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;  

};






0 0
原创粉丝点击