加入单词时 路径上每个点得count值都加一
查询直接输出 单词节点的count值
#include <cstdio>
#include <cstring>
#define sf scanf
#define pf printf
using namespace std;
struct Trie_node{
int count;
struct Trie_node* next[26];
}Root;
typedef Trie_node* P_node;
int idx(char x){
return x - 'a';
}
void Insert(char* s){
int len = strlen(s);
P_node cur = &Root;
for(int i = 0;i < len;++i){
P_node& next = cur -> next[idx(s[i])];
if(next == NULL){
next = new Trie_node;
next -> count = 0;
for(int i = 0;i < 26;++i) next -> next[i] = NULL;
}
cur = next;
cur -> count++;
}
}
int Search(char *s){
int len = strlen(s);
P_node cur = &Root;
for(int i = 0;i < len;++i){
cur = cur -> next[idx(s[i])];
if(cur == NULL) return 0;
}
return cur -> count;
}
int main(){
char s[15];
while( gets(s) && strlen(s) ){
Insert(s);
}
while( gets(s) != 0 && strlen(s) ){
pf("%d\n",Search(s));
}
return 0;
}
Trie树增删查操作

本文介绍了一种使用Trie树实现字符串插入与查询的方法。通过遍历字符串并在Trie树中创建相应节点来完成插入操作,同时记录路径上的节点出现次数。查询操作则返回指定单词在之前插入过程中的出现次数。
9万+

被折叠的 条评论
为什么被折叠?



