String set
Maintain a set of strings, supporting the following two operations:
-
+s
, which inserts string s into the set -
?s
, which queries the number of string starts with the string s
Input
The first line contains an integer m, which denotes the number of operations.
The following m lines denote the operations.
(1≤m≤100000,1≤|s|≤10,si∈{a,b})
Ouptut
For each operations of the second kind, output the result in seperated lines.
Sample input
5
+a
+ab
?a
+a
?a
Sample output
2
3
今天刷的一题关于字典树的题,题目是统计前缀的,然后从网上找了几篇博客看了看,然后套了模板,改了下就行了,感觉上和二叉树的原理很像,只不过这棵字典树有26个叉,也就是每个几点有26个孩子,实现也比较简单,看见群里有大神写得超短。。递归插入,递归查询,而且效率还挺高的。。
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define SIZE 15
#define LETTER_NUM 26
using namespace std;
struct node{
int count;
node *next[LETTER_NUM];
}*root;
void insert(char *s){
int i = 0, j;
node *p = root;
while(s[i]){
if(p->next[s[i] - 'a'] == NULL){ //如果不存在当前的单词,则新开辟一个节点
node *newNode = (node *)malloc(sizeof(node));
for(j = 0;j < LETTER_NUM;j++) //初始化新节点的26个孩子
newNode->next[j] = NULL;
newNode->count = 0;
p->next[s[i] - 'a'] = newNode; //让新节点的父亲指向它
p = p->next[s[i] - 'a'];
} else
p = p->next[s[i] - 'a'];
p->count = p->count + 1; //无论当前字符串是否存在,都将前缀的数目+1
i++;
}
}
int find(char *s) {
int i = 0;
node *p = root;
while(p != NULL&&s[i]){ //类似二叉树的查询
p=p->next[s[i]-'a'];
i++;
}
return p == NULL ? 0 :p->count; //若没有这个前缀,返回0
}
char* cut(char s[], char t[]){
int i, len = strlen(s);
for(i = 1;i < len;i++)
t[i - 1] = s[i];
t[len - 1] = '\0';
return t;
}
int main(){
char s[SIZE], t[SIZE];
int n, i;
root = (node *)malloc(sizeof(node));
for(i = 0;i < LETTER_NUM;i++)
root->next[i] = NULL;
cin >> n;
for(i = 0;i < n;i++){
cin >> s;
cut(s, t);
if(s[0] == '+')
insert(t);
else
cout << find(t) <<endl;
}
return 0;
}