您的位置:首页 > 其它

字符串匹配算法之二------Trie字典树

2015-12-29 13:01 351 查看
Trie算法:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
const int MAX = 26;
class Trie{
private:
struct TrieNode{
bool isTerminal;
struct TrieNode **tbl;
TrieNode():tbl(new struct TrieNode*[MAX]), isTerminal(false){
for (int i = 0; i != MAX; ++ i)
tbl[i] = NULL;
}
};
typedef struct TrieNode *pTrieNode;
pTrieNode root;
public:
Trie():root(new TrieNode){}
~Trie(){
deleteTrie(root);
}
void deleteTrie(pTrieNode trie);
bool insert(string word);
bool search(string word);
};

/*
*************************************************
功能   : 删除以trie为父节点的trie树,包括每个节点里面的每个表
参数   : trie
返回值 : 无
-------------------------------------------------
备注   :
-------------------------------------------------
作者   :Xu Weibin
时间   :2015-12-25
*************************************************
*/
void Trie::deleteTrie(pTrieNode trie){
if (trie == NULL)
return;
for (int i = 0; i !=MAX; ++ i){
if (trie->tbl[i] != NULL){
deleteTrie(trie->tbl[i]);
}
}
delete trie;
}

/*
*************************************************
功能   : 在以root为根节点的trie树中插入单词word
参数   : word,插入单词;
返回值 : true表示是否插入成功,false表示插入失败;
-------------------------------------------------
备注   :
-------------------------------------------------
作者   :Xu Weibin
时间   :2015-12-25
*************************************************
*/
bool Trie::insert(string word){
int word_len = word.size();
int i = 0;
pTrieNode current_node = root;
int char_pos_at_tbl;
while (i != word_len){
char_pos_at_tbl = word.at(i) - 'a';
//不存在该字母的节点,创建一个
if (current_node->tbl[char_pos_at_tbl] == NULL){
current_node->tbl[char_pos_at_tbl] = new TrieNode;
if (!current_node->tbl[char_pos_at_tbl])
return false;  //创建节点失败
}
current_node = current_node->tbl[char_pos_at_tbl];
++ i;
}
current_node->isTerminal = true;
return true;
}

/*
*************************************************
功能   : 在以root为根节点的trie树中查找单词word
参数   : word,查找单词;
返回值 : true表示查找成功,false表示查找失败;
-------------------------------------------------
备注   :
-------------------------------------------------
作者   :Xu Weibin
时间   :2015-12-25
*************************************************
*/
bool Trie::search(string word){
int word_len = word.size();
int i = 0;
pTrieNode current_node = root;
int char_pos_at_tbl;
while(i != word_len){
char_pos_at_tbl = word.at(i) - 'a';
if (current_node->tbl[char_pos_at_tbl] == NULL){
return false;
}
else{
//判断是否到达字符串末尾
if (i == word_len - 1){
if (current_node->tbl[char_pos_at_tbl]->isTerminal){
return true;
}
else{
return false;
}
}
current_node = current_node->tbl[char_pos_at_tbl];
++ i;
}
}
}

int main(int argc, char *argv[])
{
Trie trie;
trie.insert("xu");
trie.insert("wei");
trie.insert("bin");
trie.insert("xuweibin");
cout << trie.search("xuweibing");

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