基于Trie树的拼音切分算法
Trie树也叫做单词查找树,是一个非常有效的索引结构,trie是由retrieval演化而来的。具体介绍请参看–> [ 维基百科 ]
Trie树结构的简单说明
Trie树是一个度m>=2的树,它的根节点不包含任何字符元素,除根节点外的其他节点都包含且只包含一个字符元素。从根节点到某一节点的唯一路径上的所有字符组成的字符串尾该节点对应的字符串。在拼音切分中,每一个节点有26个孩子节点,对应26个英文字母。
通过Trie树的搜索可以深入理解递归。不过这并不是很好的一种方式,属于暴力搜索,时间复杂度为O(n^2)。
代码:
#include <iostream>
#include <conio.h>
using namespace std;
char stc[20];
int last = 0;
char* Stc[20];//主函数中需要初始化Stc[0]为s-1
int Last = 1;
typedef struct trietree{
int flag;
char data;
trietree* children[27];
}*node, *trie;
void MakeNull(trie &r)
{
if(r)
for(int i=1;i<=26;i++)
r->children[i-1] = NULL;
r->flag = 0;
r->data = 0;
}
bool Empty(trie r)
{
if(r != NULL)
return false;
return true;
}
void AddNode(node &n, int i)
{
if(n->children[i-1])
return;
n->children[i-1] = new trietree;
MakeNull(n->children[i-1]);
n->children[i-1]->data = i+96;
}
void AddPinYin(trie &r, char s[])
{
int i = 0;
int index;
char c = *(s+i);
node n = r;
while(c != 0){
index = (int)c-96;
if(n->children[index-1] == NULL)
AddNode(n, index);
n = n->children[index-1];
c = *(s+(++i));
}
n->flag = 1;
}
void CreateTrie(trie &t)
{
char str[405][7] = {
"a","ai","an","ang","ao","ba","bai","ban","bang","ibao","bei","ben","beng","bi","bian","biao","bie","bin","bing","bo","bu","ca","cai","can","cang","cao","ce",