2018.6.8(prefex tree)

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

struct Trie
{
    int pass;
    int end;
    Trie *next[26];
};

void Initial(Trie *node)//传入参数前,确保实参已经分配好空间和内存;
{
    node->pass=0;
    node->end=0;
    for(int i=0;i<26;i++)
        node->next[i]=NULL;
}

void Create_Trie(Trie *root,string words)
{
    Trie *current_point=root;
    int len=words.length();
    for(int i=0;i<len;i++)
    {
        int index=words[i]-'a';
        if(current_point->next[index]==NULL)
        {
            current_point->next[index]=new Trie;
            Initial(current_point->next[index]);
        }
        current_point=current_point->next[index];
        current_point->pass++;
    }
    current_point->end++;
}
bool Search(Trie *root,string words)
{
    Trie *current_point=root;
    int len=words.length();
    for(int i=0;i<len;i++)
    {
        int index=words[i]-'a';
        if(current_point->next[index]==NULL)
            return false;
        current_point=current_point->next[index];
    }
    return current_point->end==0?false:true;
}
int main()
{
    Trie *root=new Trie;
    Initial(root);

    string words;
    while(cin>>words&&words!="end")
        Create_Trie(root,words);
    while(cin>>words&&words!="end")
    {
        if(Search(root,words))
            cout<<"YES\n";
        else
            cout<<"NO\n";
    }

    delete root;
    return 0;
}

版权声明:本文为Violet_ljp原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。