字典树/前缀树

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;
}
相关推荐
未知陨落21 分钟前
LeetCode:81.爬楼梯
算法·leetcode
SHtop1140 分钟前
排序算法(golang实现)
算法·golang·排序算法
Rain_is_bad1 小时前
初识c语言————数学库函数
c语言·开发语言·算法
呆瑜nuage1 小时前
c++之AVL树
c++
磨十三2 小时前
C++ 类型转换全面解析:从 C 风格到 C++ 风格
java·c语言·c++
艾醒2 小时前
大模型面试题剖析:模型微调中冷启动与热启动的概念、阶段与实例解析
深度学习·算法
新学笺3 小时前
数据结构与算法 —— 从基础到进阶:带哨兵的单向链表,彻底解决边界处理痛点
算法
oioihoii3 小时前
从汇编角度看C++优化:编译器真正做了什么
java·汇编·c++
危险库3 小时前
【UE4/UE5】在虚幻引擎中创建控制台指令的几种方法
c++·ue5·游戏引擎·ue4·虚幻
智者知已应修善业3 小时前
【51单片机计时器1中断的60秒数码管倒计时】2023-1-23
c语言·经验分享·笔记·嵌入式硬件·算法·51单片机