字典树
#include <iostream>
#include <vector>
using namespace std;
typedef struct TireNode{
bool isWord;
TireNode* next[26]{};
TireNode()
{
isWord = false;
for (auto & i : next) {
i = nullptr;
}
}
}TireNode;
void insert(TireNode* root,string str)
{
TireNode* ptr = root;
char ch;
for(int i=0;i<str.size();i++)
{
ch = str.at(i);
if(ptr->next[ch-'a'] == nullptr)
{
ptr->next[ch-'a'] = new TireNode();
}
ptr = ptr->next[ch-'a'];
if(i==str.size()-1)
{
ptr->isWord = true;
break;
}
}
}
bool search(TireNode* root,string str)
{
TireNode* ptr = root;
char ch;
for(int i=0;i<str.size();i++)
{
ch = str.at(i);
if(ptr->next[ch-'a']!=nullptr)
{
ptr = ptr->next[ch-'a'];
if(i==(str.size()-1)&&ptr->isWord)
return true;
}
}
return false;
}
string maxProfix(TireNode* root,string str)
{
TireNode* ptr = root;
string s;
char ch;
for (int i = 0; i < str.size(); ++i) {
ch = str.at(i);
if(ptr->next[ch-'a']!= nullptr)
{
s.push_back(ch);
ptr = ptr->next[ch-'a'];
}
else
{
break;
}
}
return s;
}
int main() {
auto * root = new TireNode();
vector<string> words;
words.emplace_back("abc");
words.emplace_back("bcd");
words.emplace_back("bcde");
words.emplace_back("bcdef");
for (const auto& word:words) {
insert(root,word);
}
string s;
while(cin>>s)
{
cout<<"搜索结果:"<<search(root,s)<<endl;
cout<<"最大前缀:"<<maxProfix(root,s)<<endl;
}
}