Trie树模板

Trie树,又称单词查找树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。


Trie树 c++模板

<span style="font-size:14px;">#include<bits/stdc++.h>
using namespace std;
#define MAX 26


class node
{
	node *next[MAX];     //每个结点的分结点A~Z 26种
	bool finish;         //单词是否插入结束
	int cnt;             //统计相同前缀出现次数
                node(){ 
	    for(int i=0;i<MAX;i++)
	        next[i]=NULL;	
                }
};

class trie
{
	node *root;
	trie(){
	    root=NULL;
	}
	void insert(const char*str)      //插入单词
	{
	    if(root==NULL)
	        root=new node;
	    Node*temp=root;
	    while(*str!='\0')
	    {
		int num=*str-'a';
		if(temp->next[num]==NULL)
			temp->next[num]=new node;
 		temp->next[num]->cnt++;
		temp=temp->next[num];
		str++;
	    }
	    temp->finish=1;
	}

	bool search(const char*str)     //查找单词是否存在
	{
	     	Node *temp=root;
		while(*str!='\0')
		{
		    int num=*str-'a';
		    if(temp->next[num]==NULL)
 				return 0;
		    temp=temp->next[num];
			str++;
		}
		return temp->finish;	    	
	}

	int count(const char* str)     //判断相同前缀出现次数。
	{
		Node *temp=root;
		while(*str!='\0')
		{
			int num=*str-'a';
			if(temp->next[num]==NULL)
			{
				return 0;
			}
			else
			{
				temp=temp->next[num];
				str++;
			}
		}
		return temp->cnt;
	}
};


int main()
{
	trie t;
	t.insert("a");
	t.insert("ab");
	t.insert("abc");
	t.insert("bcde");
	cout<<t.search("bcde")<<endl;
	cout<<t.count("a")<<endl;
	return 0;
}</span>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值