trie tree(字典树)

时间:2023-03-09 15:57:02
trie tree(字典树)

hihocoder题目(http://hihocoder.com/problemset):#1014  trie树

 #include <iostream>
using namespace std;
class trieTree
{
public:
trieTree()
{
isword=false;
for (int i=;i<;i++)
{
next[i]=NULL;
}
}
~trieTree()
{
for (int i=;i<;i++)
{
if (next[i]!=NULL)
{
destory(next[i]);
}
}
}
void destory(trieTree* index);
int insertWord(char*);
int searchWord(char*);
int findWord(trieTree* index);
private:
trieTree* next[];
bool isword;
};
int main()
{
int dictionarySize;
trieTree root;
char word[];
cin>>dictionarySize;
int i=;
for(i=;i<dictionarySize;i++)
{
cin>>word;
root.insertWord(word);
}
cin>>dictionarySize;
for(i=;i<dictionarySize;i++)
{
cin>>word;
cout<<root.searchWord(word)<<endl;
} return ;
}
int trieTree::insertWord(char* word)
{
trieTree* index=this;
while(*word)
{
if(!index->next[*word-'a'])
{
index->next[*word-'a']=new trieTree;
}
if (!index->next[*word-'a'])
{
return -;
}
else
{
index=index->next[*word-'a'];
}
word++;
}
index->isword=true;
return ;
}
int trieTree::searchWord(char* word)
{
trieTree* index=this;
int count=;
while(*word)
{
if(index->next[*word-'a']==NULL)
{
return ;
}
index=index->next[*word-'a'];
word++;
}
count=findWord(index);
return count;
}
int trieTree::findWord(trieTree* index)
{
int count=;
if(index->isword)
count++;
for(int i=;i<;i++)
{
if(index->next[i]!=NULL)
{
count+=findWord(index->next[i]);
}
}
return count;
}
void trieTree::destory(trieTree* index)
{
for (int i=;i<;i++)
{
if (index->next[i]!=NULL)
{
destory(index->next[i]);
index->next[i]=NULL;
}
}
delete index;
}

通过编译之后,发现提交上去还是错了,Wrong Answer!