trie树
http://blog.csdn.net/terro/article/details/1745699
Trie数:思想表示词典数,即用树形结构表示词典。
仅需要修改TrieNode中参数即可。
1)可以用来查找相同前缀,最长的前缀
2)查找相同前缀的个数
3)查找某个单词是否出现过
- #include <iostream>
- using namespace std;
- #include <stdio.h>
- #include <string.h>
- #define MAX 26
- typedef struct TrieNode {
- int nCount;
- struct TrieNode *next[MAX];
- }TrieNode;
- TrieNode Memory[1000000]; //保存内容和trie先序遍历结果一致,创建树按照先序创建。
- int alloc = 0;
- void initTrieRoot(TrieNode **pRoot) {
- *pRoot = NULL;
- }
- TrieNode *createTrieNode(){
- int i;
- TrieNode *p=NULL;
- p=&Memory[alloc++];
- p->nCount = 1;
- for(i=0;i<MAX;i++) {
- p->next[i] = NULL;
- }
- return p;
- }
- void insertTrie(TrieNode *pRoot,char *s) {
- int i,k;
- if(pRoot==NULL || *s=='\0') {
- return ;
- }
- TrieNode *p=pRoot;
- i = 0;
- while(s[i]!='\0'){
- k=s[i++]-'a';
- if(p->next[k]!=NULL){
- p->next[k]->nCount++;
- } else {
- p->next[k] = createTrieNode();
- }
- p=p->next[k];
- }
- }
- int searchTrie(TrieNode * pRoot,char *s) {
- TrieNode *p;
- int i,k;
- if(pRoot==NULL){
- return 0;
- }
- p = pRoot;
- i=0;
- while(s[i]){
- k=s[i++]-'a';
- if(p->next[k]==NULL) return 0;
- p = p->next[k];
- }
- return p->nCount;
- }
- int main(){
- memset(Memory,0,sizeof(Memory));//初始化数空间
- TrieNode *root=createTrieNode(); //根节点
- int n;
- cin>>n;
- char input[32];
- for(int i=0;i<n;i++) {
- cin>>input;
- insertTrie(root,input);
- }
- // TrieNode *tmp = root; //遍历输出,要控制输出条件,避免进入死循环,用不变量模式进行控制。
- // while(tmp!=NULL) {
- // int j=0;
- // for(j=0;j<MAX;j++) {
- // if(tmp->next[j]!=NULL) {
- // cout<<j<<"\t";
- // break;
- // }
- // }
- // if(j<MAX) tmp = tmp->next[j]; //如果不填加判断条件,则进入空指针,如j > MAX .
- // else break;
- // }
- // cout<<endl;
- // }
- // char find[] = {'b','a','a','b','b'};
- // char *find = "babb";
- char find[11];
- int m;
- cin>>m;
- int i=0;
- while(i<m) {
- cin>>find;
- cout<<searchTrie(root,find)<<endl;
- i++;
- }
- // for(int i=0;i<alloc;i++) {
- // cout<<Memory[i].nCount<<"\t";
- // }
- cout<<endl;
- return 0;
- }