字典树/前缀树

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;
}
相关推荐
NuyoahC1 小时前
笔试——Day46
c++·算法·笔试
Keying,,,,1 小时前
力扣hot100 | 图论 | 200. 岛屿数量、994. 腐烂的橘子、207. 课程表、208. 实现 Trie (前缀树)
算法·leetcode·图论
啊吧怪不啊吧2 小时前
C++之list类的代码及其逻辑详解 (中)
开发语言·数据结构·c++·list
hai_qin2 小时前
三,设计模式-抽象工厂模式
c++·设计模式·抽象工厂模式
永不停转2 小时前
详谈 QLayout::SizeConstraint 和 QSizePolicy 对 QWidget 尺寸的影响
c++·qt
cwplh2 小时前
Codeforces1043 A至F 题解
算法
楼田莉子3 小时前
C++算法学习专题:滑动窗口
开发语言·数据结构·c++·学习·算法·leetcode
2501_924731113 小时前
智慧矿山误报率↓83%!陌讯多模态融合算法在矿用设备监控的落地优化
人工智能·算法·目标检测·视觉检测
炸膛坦客3 小时前
C++ 学习与 CLion 使用:(四)常量和变量,包括字面常量和符号常量
开发语言·c++·学习
特立独行的猫a3 小时前
C/C++三方库移植到HarmonyOS平台详细教程(补充版so库和头文件形式)
c语言·c++·harmonyos·napi·三方库·aki