字典树/前缀树

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***s6321 天前
C++移动语义优化
开发语言·c++
稚辉君.MCA_P8_Java1 天前
Gemini永久会员 Go 实现动态规划
数据结构·后端·算法·golang·动态规划
快手技术1 天前
快手 & 南大发布代码智能“指南针”,重新定义 AI 编程能力评估体系
算法
Murphy_lx1 天前
C++ std_stringstream
开发语言·c++·算法
Mr.Winter`1 天前
基于Proto3和单例模式的系统参数配置模块设计(附C++案例实现)
c++·人工智能·单例模式·机器人
CoovallyAIHub1 天前
超越YOLOv8/v11!自研RKM-YOLO为输电线路巡检精度、速度双提升
深度学习·算法·计算机视觉
哭泣方源炼蛊1 天前
HAUE 新生周赛(七)题解
数据结构·c++·算法
q***64971 天前
SpringMVC 请求参数接收
前端·javascript·算法
Lwcah1 天前
Python | LGBM+SHAP可解释性分析回归预测及可视化算法
python·算法·回归
小此方1 天前
从零开始手搓堆:核心操作实现 + 堆排序 + TopK 算法+ 向上调整 vs 向下调整建堆的时间复杂度严密证明!
开发语言·数据结构·算法