AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

字符串基本算法(欢迎补充)

作者: 作者的头像   乡村守望者 ,  2020-08-15 20:37:36 ,  所有人可见 ,  阅读 671


2


4

字符串基本算法(欢迎补充)

1.KMP算法

#include<iostream>
using namespace std;
const int N = 1000010;
int n,m;
int ne[N];
char p[N],s[N];
int main()
{
    cin>>n>>p+1>>m>>s+1;
    for(int i=2,j=0;i<=n;++i)
    {
        while(j&&p[j+1]!=p[i])j=ne[j];
        if(p[j+1]==p[i])j++;
        ne[i]=j;
    }
    for(int i=1,j=0;i<=m;++i)
    {
        while(j&&p[j+1]!=s[i])j=ne[j];
        if(p[j+1]==s[i])j++;
        if(j==n)
        {
            printf("%d ",i-n);
            j=ne[j];
        }
    }
    return 0;
}

2.Trie算法

#include<iostream>
using namespace std;
const int N = 100010;
int son[N][26],idx;
int cot[N];
char str[N],op[2];
int n;
void insert()
{
    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];
    }
    cot[p]++;
}
int query()
{
    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 cot[p];
}
int main()
{
    cin>>n;
    while(n--)
    {
        scanf("%s%s",op,str);
        if(*op=='I')insert();
        else printf("%d\n",query());
    }
    return 0;
}

3.字符串哈希

#include<iostream>
using namespace std;
typedef unsigned long long ULL;
const int N = 100010,P=131;//131 13331
char str[N];
int n,m;
ULL h[N];
ULL p[N];
ULL get(int l,int r)
{
    return h[r]-h[l-1]*p[r-l+1];
}
int main()
{
    cin>>n>>m;
    cin>>str+1;
    p[0]=1;
    for(int i=1;i<=n;++i)
    {
        p[i]=p[i-1]*P;
        h[i]=h[i-1]*P+str[i];
    }
    while(m--)
    {
        int l1,r1,l2,r2;
        scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
        if(get(l1,r1)==get(l2,r2))
            puts("Yes");
        else puts("No");
    }
    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息