字典树
解释在代码注释中,详情写在语雀中
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int tree[100001][27]; //i记录的是上一个节点(相当于链表中的一个申请的节点)是第几个(cnt),j是上一个节点指向的字符,tree[i][j]储存节点的位置,也可以判断是否存在
int exist[100001]; //以这个节点(cnt)结尾的点是否存在
int cnt = 0;
//这里的每个cnt节点就相当于链表中的一个new节点
void Insert(); //插入操作
bool Find(); //查询操作
int main()
{
//输入5个单词作为测试
for (int i = 1; i <= 5; i++)
{
cout << "输入新增单词:";
Insert();
}
//查询
for (int i = 1; i <= 2; i++)
{
cout << "输入查询单词:\n";
if (Find())
cout << "存在\n";
else cout << "不存在\n";
}
return 0;
}
void Insert()
{
char s[30];
cin.getline(s, 30);
//getchar();
int last = 0; //前一个节点(cnt)
int ch=0; //记录字符串的前一个字符是什么
for (int i = 0; i < strlen(s); i++)
{
ch = s[i] - 'a';//这样操作ch就是一个数字了
if (!tree[last][ch]) tree[last][ch] = ++cnt; //插入操作如果这样的字符不存在就添加
last = tree[last][ch]; //更新上一个字符的位置
}
exist[last]++; //这样的字符串存在且次数+1
}
bool Find()
{
char s[30];
cin.getline(s, 30);
//getchar();
int last = 0;
int ch = 0;
for (int i = 0; i < strlen(s); i++)
{
ch = s[i] - 'a';
//与insert函数不同的是,这里遇到不存在或不匹配的地方就证明不存在直接退出,insert函数不存在是更新添加
if (!tree[last][ch]) return false;
last = tree[last][ch];
}
return true;
}