trie树(字典树)

String set

Maintain a set of strings, supporting the following two operations:

  1. +s, which inserts string s into the set

  2. ?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.

(1m100000,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;	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值