code
Function:
1. Insert
2. Find word
3. Find prefix
Simple interaction
#include <bits/stdc++.h>
#define MAXS 26 //节点的孩子的个数(都是小写字母)
using namespace std;
struct TrieNode
{
TrieNode *child[MAXS];
bool isword; //当前节点是否为单词
TrieNode():isword(false) //构造函数
{
for(int i=0;i<MAXS;i++)
child[i]=0;
}
};
class TrieTree
{
public:
vector<TrieNode *> _node_vec;
TrieNode _root; //根节点
TrieTree() {
} //构造
~TrieTree() //析构
{
for(int i=0;i<_node_vec.size();i++)
delete _node_vec[i];
}
TrieNode *new_node(); //创建新节点
void insert(const char*); //插入单词
bool search(const char*); //查找单词
bool startsWith(const char*); //查找前缀
};
TrieNode * TrieTree::new_node()
{
TrieNode *node=new TrieNode();
_node_vec.push_back(node);
return node;
}
void TrieTree::insert(const char *word)
{
TrieNode *ptr=&_root;
while(*word)
{
int pos=*word-'a'; //转换成对应的数字
if(!ptr->child[pos])
{
ptr->child[pos]=new_node();
}
ptr=ptr->child[pos];
word++;
}
ptr->isword=true; //最后一个字母的地方标记
}
bool TrieTree::search(const char *word)
{
TrieNode *ptr=&_root;
while(*word)
{
int pos=*word-'a';
if(!ptr->child[pos])
return false;
ptr=ptr->child[pos];
word++;
}
return ptr->isword;
}
bool TrieTree::startsWith(const char *word)
{
TrieNode *ptr=&_root;
while(*word)
{
int pos=*word-'a';
if(!ptr->child[pos])
return false;
ptr=ptr->child[pos];
word++;
}
return true; //循环结束说明这个前缀一定存在
}
int main (void)
{
cout<<"请输入想要插入的单词数量:";
int n;
cin>>n;
printf("下面输入%d个小写单词:\n",n);
TrieTree trie;
for(int i=0;i<n;i++)
{
printf("#%d:",i+1);
string s;
char *str;
cin>>s;
str=&s[0];
trie.insert(str);
}
while(1)
{
cout<<"请输入要查询的项目id:1.单词 2.单词前缀(输入其他任意字符退出)\n";
char id;
cin>>id;
if(id!='1'&&id!='2')
{
cout<<"May you succeed!\n";
return 0;
}
char *str;
string s;
cout<<"请输入要查询的内容:\n";
cin>>s;
str=&s[0];
switch(id)
{
case '1':
if(trie.search(str))
cout<<"Yes!\n";
else
cout<<"No!\n";
break;
case '2':
if(trie.startsWith(str))
cout<<"Yes!\n";
else
cout<<"No!\n";
break;
default:
cout<<"May you succeed!\n";
return 0;
}
}
return 0;
}