欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Trie字符串统计(字典树查询字符串出现次数)

程序员文章站 2022-04-30 20:38:12
...

Trie字符串统计(字典树查询字符串出现次数)
Trie字符串统计(字典树查询字符串出现次数)

思路:字典树

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <set>
#include <sstream>
#include<string>
#include<queue>
#include<stack>
#include<map>
#include<cmath>
#include<cctype>
#include<cstring>
#include<cstdlib>
#define MAXX 100005
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
//#include<bits/stdc++.h>
using namespace std;
//const int MAX =100;
const double PI = 3.14159265359;
//const int mod = 1e9 + 7;
int n, m;
struct node
{
    int x, y;ll num;
    bool operator <(const node other)const
    {
        return num > other.num;

    }
};
int trie[400001][26], len, root, tot,sum[400001];
bool p;

void insert(string s)
{
    len = s.size();
    root = 0;
    for (int i = 0; i < len; i++)
    {
        int id = s[i] - 'a';
        if (!trie[root][id]) trie[root][id] = ++tot;
        root = trie[root][id];
    }
    sum[root]++;
}
int search(string s)
{
    root = 0;
    len = s.size();
    for (int i = 0; i < len; i++)
    {
        int id = s[i] - 'a';
        if (!trie[root][id])return 0;
        root = trie[root][id];
    }
    return sum[root];
}
int main()
{
   int t;
   cin>>t;
   while(t--)
   {

       string x,y;
       cin>>x>>y;
       if(x[0]=='I')
       {
           insert(y);
       }
       else
       {
           cout<<search(y)<<endl;;
       }
   }
    return 0;

}


相关标签: 字典树