字典树TrieC++实现
实现代码
#include <bits/stdc++.h>
using namespace std;
class Trie {
private :
static const int MAX_SIZE = 1024 ;
static const int SIGMA_SIZE = 26 ;
int character[ MAX_SIZE] [ SIGMA_SIZE] ;
bool tag[ MAX_SIZE] ;
int size;
int index ( char c) ;
public :
Trie ( ) ;
void insert ( string str) ;
bool search ( string str) ;
} ;
Trie:: Trie ( ) {
size = 1 ;
memset ( character[ 0 ] , 0 , sizeof ( character[ 0 ] ) ) ;
}
int Trie:: index ( char c) {
return c - 'a' ;
}
void Trie:: insert ( string str) {
int currentLevel = 0 ;
for ( int i = 0 ; i < str. size ( ) ; i++ ) {
int c = index ( str[ i] ) ;
if ( ! character[ currentLevel] [ c] ) {
memset ( character[ size] , 0 , sizeof ( character[ size] ) ) ;
tag[ size] = false ;
character[ currentLevel] [ c] = size++ ;
}
currentLevel = character[ currentLevel] [ c] ;
}
tag[ currentLevel] = true ;
}
bool Trie:: search ( string str) {
int currentLevel = 0 ;
for ( int i = 0 ; i < str. size ( ) ; i++ ) {
int c = index ( str[ i] ) ;
if ( ! character[ currentLevel] [ c] ) {
return false ;
}
currentLevel = character[ currentLevel] [ c] ;
}
return tag[ currentLevel] ;
}
int main ( int argc, char const * argv[ ] )
{
string str;
Trie trie;
while ( cin >> str) {
trie. insert ( str) ;
cin >> str;
printf ( "%s\n" , trie. search ( str) ? "Exist" : "Not found" ) ;
}
return 0 ;
}
算法思路
建立Trie 根据输入字符串的顺序,若字符串的前缀已经存在于字典树中,则沿着对应的子树搜索,直到不匹配。不匹配时,新建节点插入字典树,不断循环,直到结束,将对应tag置为true表示这是一个存放在字典树中的单词 搜索 根据输入字符串的顺序,一次搜索,若字符串的前缀已经存在于字典树中,则沿着对应的子树搜索,若出现不匹配则返回false,否则返回tag,若tag为true则表示欲搜索的字符串是字典树Trie中存放的单词,否则表示存在一个字符串的前缀是欲搜索的这个字符串,但字典树Trie不存在这个单词
character数组 存放的是字典树Trie当前结点的孩子节点所在的层的索引(层数,二维数组行标),其所有的孩子节点都该层中,数组的下标则对应相应的字符,根节点不对应任何字符
输入数据
eclipse
eclipse
ecs
cs
program
pro
输出结果
Exist
Not found
Not found
鸣谢
最后
由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!