传送门:Censor
题目大意
给定一个字符串A和一个字符串B,如果如果B中存在A字符串,就在B中把A字符串去掉,输出最后去掉A字符串之后B字符串
解题思路
这个题目用到了字符串哈希和前缀和的思想!
我们把输入的A字符串哈希为一个整数,然后把用一个数组hb[i]表示B字符串中前i个的哈希值,当i大于字符串A的长度的时候就判断i-lena,i这个区间的哈希值是不是等于A串的。
AC代码
#include<cstdio>
#include<cstring>
const int MAXN = 5e6+5;
const int Hash = 27;
typedef unsigned long long ULL;
char strA[MAXN],strB[MAXN];
char tmp[MAXN];
ULL hb[MAXN];
ULL preHash[MAXN];
void presolve()
{
preHash[0] = 1;
for(int i=1;i<MAXN;i++)
preHash[i] = preHash[i-1]*Hash;
}
int main()
{
presolve();
while(~scanf("%s%s",strA,strB))
{
int lenA = strlen(strA),lenB = strlen(strB);
ULL ha=0,top=0;
if(lenA>lenB){
printf("%s\n",strB);
continue;
}
hb[0] = 0;
for(int i=0;i<lenA;i++) ha=ha*Hash + strA[i]-'a'+1;
for(int i=0;i<lenB;i++){
tmp[top++] = strB[i];
hb[top] = hb[top-1]*Hash + strB[i]-'a'+1;
if(top>=lenA &&hb[top]-hb[top-lenA]*preHash[lenA]==ha) {
top-=lenA;
}
}
for(int i=0;i<top;i++) printf("%c",tmp[i]);
puts("");
}
return 0;
}

本文介绍了一种利用字符串哈希和前缀和解决字符串匹配问题的方法。通过将字符串转换为整数哈希值,可以快速查找并删除目标子串。文章提供了完整的AC代码实现。
928

被折叠的 条评论
为什么被折叠?



