KMP字符串查找HDU1251统计难题

http://acm.hdu.edu.cn/showproblem.php?pid=1251

Problem Description

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

 

Input

输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.

 

Output

对于每个提问,给出以该字符串为前缀的单词的数量.

 

Sample Input

 

banana band bee absolute acm ba b band abc

 

Sample Output

 

2 3 1 0

#include<iostream>
#include<string>
using namespace std;
struct trieNode{
    int count;//统计单词前缀出现的次数
    trieNode* next[26];//指向各子树的指针
    bool exit;//标记该结点处是否构成单词

    trieNode():count(0),exit(false){
        for (int i = 0; i < 26; i++){
            next[i] = NULL;
        }
    }
};
void trieInsert(trieNode* root, string &word){
    trieNode *node = root;
    int id;
    int len = word.size();
    int i = 0;
    while (i < len){
        id = word[i]-'a';//挨个找字符
        if (node->next[id] == NULL){
            node->next[id] = new trieNode();
        }
//如果字符为空,说明还没这个字符,则需要添加。
        node = node->next[id];//移动到下一个节点;
        node->count += 1;
//赋值为count数加1,node移动到下一个节点;
        i++;//字符移动;
    }
    node->exit = true;//单词结束,可以构成一个单词
}

int trieSearch(trieNode*root, string &word){

    trieNode* node = root;
    int len = word.size();
    int i = 0;
    while (i < len){
        int id = word[i] - 'a';
        if (node->next[id] != NULL){
            node = node->next[id];
            i++;//如果不为空,再看下一个字符。
        }
        else{
            return 0;//为空则直接return 0;
        }
    }
    return node->count;//返回字符串位置;
}
int main()
{
    trieNode *root = new trieNode();

    string word;
    int flag = false;
    while (getline(cin, word)&&word.compare("")!=0){
                trieInsert(root, word);
    }
     while(cin>>word)
            cout << trieSearch(root, word) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/85451931