字典树Trie---C++实现

#include <iostream>
#include <string>
using namespace std;

/*
*Trie树 字典树C++实现
*/

class TrieNode {
public:
	TrieNode() {
		end = path = 0;
		for (int i = 0; i < 26; i++) {
			nexts[i] = NULL;
		}
	};
public:
	int end;//以该字符结尾的单词个数
	int path;//以该字符之前的字符串为前缀的单词个数
	TrieNode* nexts[26];
};

//插入单词
void insert(TrieNode* head, const string& word) {
	if (head && word.size()) {
		TrieNode* node = head;
		for (int i = 0; i < word.size(); i++) {
			if (node->nexts[word[i] - 'a'] == NULL) {
				node->nexts[word[i] - 'a'] = new TrieNode();
			}
			node->path++;
			node = node->nexts[word[i] - 'a'];
		}
		node->end++;
		//该情况是单词结尾的位置  前缀数也加1
		node->path++;
	}
}

//求word出现的次数
int wordTimes(TrieNode* head, const string& word) {
	if (head && word.size()) {
		TrieNode* node = head;
		for (int i = 0; i < word.size(); i++) {
			if (node->nexts[word[i] - 'a'] == NULL) {
				return 0;
			}
			node = node->nexts[word[i] - 'a'];
		}
		return node->end;
	}
	return 0;
}

//求以word为前缀的单词数
int wordPrefix(TrieNode* head, const string& word) {
	if (head && word.size()) {
		TrieNode* node = head;
		for (int i = 0; i < word.size(); i++) {
			if (node->nexts[word[i] - 'a'] == NULL) {
				return 0;
			}
			node = node->nexts[word[i] - 'a'];
		}
		return node->path;
	}
	return 0;
}

//删除trie中的一个word
void deleteWord(TrieNode* head, const string& word) {
	if (wordTimes(head, word)) {
		TrieNode* node = head;
		for (int i = 0; i < word.size(); i++) {
			//如果此时path为1 则之后所有的结点都可以直接删除 
			if (node->nexts[word[i]-'a']->path-- == 1) {
				node = NULL;
				return;
			}
			node = node->nexts[word[i] - 'a'];
		}
		node->end--;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值