跳到正文

个人记录

字典树

Meovow约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

字典树的定义

字典树是一种树形结构,可以用来处理字符串的前缀匹配问题,就比如你输入 “abc”,它能够快速找到所有以 “abc” 开头的单词字符串

字典树的实现

  1. 插入操作(往树里加单词)

从根节点出发。就比如说插入 “apple”,就沿着 a→p→p→l→e 的路径走,最后在 e 节点打上“完整标记”,表示这个字符串结束了。

  1. 查找操作(查单词是否存在)

从根节点开始,如果能走完所有字符且最后节点有“完整标记”,就说明字符串存在。比如查 “app”这个字符串,但是树里只有 “apple”,也就是“完整标记”在 e 那里,也就是找到 p 的时候那个点没有“完整标记”,就返回 0。

  1. 前缀匹配(查是否有单词以某前缀开头)

跟查找差不多。就比如前缀是 “app”,只要树里有任意单词是以 app 开头就返回 true,不管是否有“完整标记”。

注意:字典树有一个致命的缺点,那就是占内存!

完整模版代码:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 3e6 + 5;
int trie[N][65] , cnt[N];
int tot;
int get_sum(char x)
{
    if (x >= 'A' && x <= 'Z')
        return x - 'A';
    if (x >= 'a' && x <= 'z')
        return x - 'a' + 26;
    return x - '0' + 52;
}
void insert(string s)
{
    int lens = s.size() , u = 0;
    for (int i = 0; i < lens; i++)
    {
        int x = get_sum(s[i]);
        if (trie[u][x] == 0)
            trie[u][x] = ++tot;
        u = trie[u][x];
        cnt[u]++;
    }
    return ;
}
int search(string s)
{
    int lens = s.size() , u = 0;
    for (int i = 0; i < lens; i++)
    {
        int x = get_sum(s[i]);
        if (trie[u][x] == 0)
            return 0;
        u = trie[u][x];
    }
    return cnt[u];
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while (t--)
    {
        for (int i = 0; i <= tot; i++)
        {
            for (int j = 0; j <= 122; j++)
                trie[i][j] = 0;
            cnt[i] = 0;
        }
        tot = 0;
        int n , q;
        cin >> n >> q;
        while (n--)
        {
            string s;
            cin >> s;
            insert(s);
        }
        while (q--)
        {
            string s;
            cin >> s;
            cout << search(s) << "\n";
        }
    }
    return 0;
}

例题

这道题就主要是查找有没有出现过,直接调用search函数即可。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 5e5 + 5;
int n, node[N][30], vis[N], tot;
int get_sum(char c)
{
    if (c >= 'a' && c <= 'z') return c - 'a';
    if (c >= 'A' && c <= 'Z') return c - 'A' + 26;
    return c - '0' + 52;
}
void insert(string s)
{
	int len = s.size(), u = 0;
	for (int i = 0; i < len; i++)
    {
		int c = get_sum(s[i]);
		if (node[u][c] == 0)
        {
            ++tot;
			node[u][c] = tot;
        }
		u = node[u][c];
	}
	vis[u]++;
	return;
}
int search(string s)
{
	int len = s.size();
	int u = 0;
	for (int i = 0; i < len; i++)
    {
		int c = get_sum(s[i]);
		if (node[u][c] == 0) return 0;
		u = node[u][c];
	}
	return vis[u]++;
}
signed main()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
    {
		string s;
		cin >> s;
		insert(s);
	}
	int m;
	cin >> m;
	while(m--)
    {
		string s;
		cin >> s;
		int x = search(s);
		if (x == 0)  cout << "WRONG\n";
		else if (x == 1) cout << "OK\n";
		else cout << "REPEAT\n";
	}
	return 0;
}
原文