其他分享
首页 > 其他分享> > [AcWIng 835] Trie字符串统计

[AcWIng 835] Trie字符串统计

作者:互联网

image
image


点击查看代码
#include<iostream>

using namespace std;
const int N = 1e5 + 10;
int son[N][26], cnt[N], idx;
char str[N];
void insert(char str[])
{
    int p = 0;
    for (int i = 0; str[i]; i ++) {
        int u  = str[i] - 'a';
        if (!son[p][u]) son[p][u] = ++ idx;
        p = son[p][u];
    }
    cnt[p] ++;
}
int query(char str[])
{
    int p = 0;
    for (int i = 0; str[i]; i ++) {
        int u = str[i] - 'a';
        if (!son[p][u]) return 0;
        p = son[p][u];
    }
    return cnt[p];
}
int main()
{
    int n;
    cin >> n;
    while (n --) {
        char op;
        cin >> op >> str;
        if (op == 'I')      insert(str);
        else if (op == 'Q')     cout << query(str) << endl;
    }
    return 0;
}

  1. 字典树适用于大小写字符串集合的插入和查询;
  2. 把字母 'a' - 'z' 用数字 '0' - '25' 进行表示;
  3. 使用数组来存储字典树,数组下标为 0 的结点既是根结点也是空结点;
  4. son[ i ][ j ] 中的 i 表示字典树的层数(也可以理解为字符串的第 i 个位置),j 表示这个位置的字符,son[ i ][ j ] 的值是下一个结点在数组中的位置
  5. cnt 用来记录以 p 位置字符为结尾的字符出现的次数;

标签:cnt,835,Trie,++,son,char,int,str,AcWIng
来源: https://www.cnblogs.com/wKingYu/p/16216216.html