左神视频:前缀树(C++版)

此文件为纯手撸.h文件,引用后调用相应的接口即可。

#pragma once
/* 前缀树(字典树)*/
#include <iostream>

using namespace std;

class TrieNode
{
public:
	int path;//当前字母被经过的次数
	int end;//当前单词出现的次数
	TrieNode *next[26];
	TrieNode()
	{
		path = 0;
		end = 0;
		for (int i = 0; i < 26; i++)
		{
			next[i] = NULL;
		}
	}
};

class Trie
{
public:
	TrieNode *root;
	Trie() 
	{
		root = new TrieNode();
	}

	void insertWord(string word)
	{
		TrieNode *p = root;
		for (int i = 0; i < word.size(); i++)
		{
			if (p->next[word[i]-'a'] == NULL)
			{
				p->next[word[i] - 'a'] = new TrieNode;
			}
			p = p->next[word[i] - 'a'];
			p->path++;
		}
		p->end++;
	}

	int searchWord(string word)
	{
		TrieNode *p = root;
		for (int i = 0; i < word.size(); i++)
		{
			if (p->next[word[i]-'a'] == NULL)
			{
				return	0;
			}
			p = p->next[word[i] - 'a'];
		}
		if (p->end!=0)
		{
			return p->end;
		}
		else
		{
			return 0;
		}
	}

	void deleteWord(string word)
	{
		TrieNode *p = root;
		if (searchWord(word))
		{
			for (int i = 0; i < word.size(); i++)
			{
				if (--p->next[word[i]-'a']->path == 0)
				{
					p->next[word[i] - 'a'] = NULL;
					return;
				}
				p = p->next[word[i] - 'a'];
			}
			p->end--;
		}
	}

	int perfixNumber(string word)
	{
		TrieNode *p = root;
		for (int i = 0; i < word.size(); i++)
		{
			if (--p->next[word[i] - 'a']->path == 0)
			{
				p->next[word[i] - 'a'] = NULL;
				return 0;
			}
			p = p->next[word[i] - 'a'];
		}
		return p->path;
	}

private:

};

/* main for test */
/*
#include "trieTree.h"
#include <iostream>

using namespace std;

int main()
{
Trie *trie = new Trie();
cout << trie->searchWord("zuo") << endl;
trie->insertWord("zuo");
cout << trie->searchWord("zuo") << endl;
trie->deleteWord("zuo");
cout << trie->searchWord("zuo") << endl;

trie->insertWord("zuo");
trie->insertWord("zuo");
trie->deleteWord("zuo");
cout << trie->searchWord("zuo") << endl;

trie->insertWord("zuoa");
trie->insertWord("zuoac");
trie->insertWord("zuoab");
trie->insertWord("zuoad");
trie->insertWord("zuoa");
cout << trie->searchWord("zuoa") << endl;
cout << trie->perfixNumber("zuo") << endl;

system("pause");
return 0;
}
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值