您的位置:首页 > 编程语言 > C语言/C++

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

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

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

它有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; }  

}
 

return
nullptr;
}  

~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)
 

return
false;
 

}
 

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)
 

return
false;
 

}
 

return
true;
 

}
 

~Trie() {  

delete
root;  

}
 

private:
TrieNode* root;  

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: