字典树/前缀树

Solution

cpp 复制代码
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
const int max_n = 1e6 + 5;
int tree[max_n][26];
int Pass[max_n];
int End[max_n];
int cnt = 1;
void insert(string word) {
	int node = 1;//从根节点开始
	Pass[node]++;
	for (int i = 0; i < word.length(); ++i) {
		int path = word[i] - 'a';
		if (tree[node][path] == 0) {
			tree[node][path] = ++cnt;
		}
		node = tree[node][path];
		Pass[node]++;
	}
	End[node]++;
}
int countWord(string word) {
	int node = 1;
	for (int i = 0; i < word.length(); ++i) {
		int path = word[i] - 'a';
		if (tree[node][path] == 0) return 0;
		node = tree[node][path];
	}
	return End[node];
}
int countPre(string pre) {
	int node = 1;
	for (int i = 0; i < pre.length(); ++i) {
		int path = pre[i] - 'a';
		if (tree[node][path] == 0) return 0;
		node = tree[node][path];
	}
	return Pass[node];
}
void delete_word(string word) {
	int node = 1;
	if (countWord(word) > 0) {
		for (int i = 0; i < word.length(); ++i) {
			int path = word[i] - 'a';
			if (--Pass[tree[node][path]] == 0) {//这里注意减的是哪个节点的Pass值
				tree[node][path] = 0;
				return;
			}
			node = tree[node][path];
		}
		End[node]--;
	}
}

void clear() {
	// 清空整个 tree 数组
	memset(tree, 0, sizeof(tree));
	// 清空 Pass 数组
	memset(Pass, 0, sizeof(Pass));
	// 清空 End 数组
	memset(End, 0, sizeof(End));
	// 重置节点计数
	cnt = 1;
}
int main() {
	insert("Fan");
	insert("Fang");
	insert("Fantasy");
	cout << countWord("Fan") << endl;
	cout << countPre("Fa") << endl;
	delete_word("Fan");
	cout << countWord("Fan") << endl;
	cout << countPre("Fan") << endl;

	
	return 0;
}
相关推荐
碧海银沙音频科技研究院1 小时前
ES7243E ADC模拟音频转i2S到 BES I2S1 Master输出播放到SPK精准分析
人工智能·算法·音视频
百度智能云1 小时前
MySQL最怕的IN大列表,被百度智能云GaiaDB治好了!查询速度提升60倍!
算法
信奥卷王1 小时前
[GESP202506 五级] 奖品兑换
数据结构·算法
似水এ᭄往昔1 小时前
【C++】--list的使用和模拟实现
开发语言·c++
十五年专注C++开发2 小时前
qtmqtt: 一个开源且好用的mqtt开源客户端
c++·qt·mqtt·开源
奶茶树2 小时前
【数据结构】二叉搜索树
数据结构·算法
小苏兮2 小时前
【数据结构】二叉搜索树
开发语言·数据结构·c++·学习·1024程序员节
腾昵猫2 小时前
程序员的自我修养(三)
c++
晨曦(zxr_0102)2 小时前
CSP-X 2024 复赛编程题全解(B4104+B4105+B4106+B4107)
数据结构·c++·算法
ai安歌2 小时前
【Rust编程:从新手到大师】 Rust 控制流深度详解
开发语言·算法·rust