hiho一下第二周——字典树

hiho一下第二周——字典树

#include <iostream>  
#include <stack>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>

#include <cstdio>    
#include <cstring>

using namespace std;
 
typedef struct Trie_node  
{  
    int count;                    // 统计单词前缀出现的次数  
    struct Trie_node* next[26];   // 指向各个子树的指针  
    bool exist;                   // 标记该结点处是否构成单词    
}TrieNode , *Trie;

TrieNode* createTrieNode()  
{  
    TrieNode* node = (TrieNode *)malloc(sizeof(TrieNode));  
    node->count = 0;  
    node->exist = false;  
    memset(node->next , 0 , sizeof(node->next));    // 初始化为空指针  
    return node;  
}

void Trie_insert(Trie root, char* word)  
{  
    Trie node = root;  
    char *p = word;  
    int id;  
    while( *p )  
    {  
        id = *p - 'a';  
        if(node->next[id] == NULL)  
        {  
            node->next[id] = createTrieNode();  
        }  
        node = node->next[id];  // 每插入一步,相当于有一个新串经过,指针向下移动  
        ++p;  
        node->count += 1;      // 这行代码用于统计每个单词前缀出现的次数(也包括统计每个单词出现的次数)  
    }  
    node->exist = true;        // 单词结束的地方标记此处可以构成一个单词  
} 

int Trie_search(Trie root, char* word)  
{  
    Trie node = root;  
    char *p = word;  
    int id;  
    while( *p )  
    {  
        id = *p - 'a';  
        node = node->next[id];  
        ++p;  
        if(node == NULL)  
            return 0;  
    }  
    return node->count;  
}  

int main()  
{  
	int argc1,argc2,ans;
    int i = 0;
    char *argv1,*argv2;
    //freopen("data.txt","r",stdin);

    Trie root = createTrieNode();     // 初始化字典树的根节点  
    char str[12] ;  
    bool flag = false; 
    cin >>  argc1;
    while(i < argc1 && cin >>str)  
    {  
        Trie_insert(root , str); 
        //cout << str << endl;
        i++; 
    } 

    i = 0;
    cin >>  argc2;
    while(i <= argc2 && cin >> str)  
    {   
        printf("%d\n",Trie_search(root , str));
        i++;
    } 
    //system("pause");  
    return 0;  
}  

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值