soj 3014: Seek the Name, Seek the Fame (字符串hash)

本文详细介绍了使用字符串哈希方法解决字符串中相同前缀后缀长度的问题,通过首尾两端维护hash值,判断是否相等来确定相同部分长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@(K ACMer)


题意:
对于一个字符串s,找出所有相同的前缀后缀长度.
分析:
一看就可以用字符串hash来搞,首位两端维护一个hash值,如果该hash值相等就说明字符串相同.


字符串hash代码

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 4e5 + 123, INF = 0x3fffffff, mod = 1e9 + 7;
typedef int ull;
char s[maxn];
int slen, seed = 131;

int main(void ){
    while (~scanf("%s", s)) {
        slen = (int)strlen(s);
        ull a = 0, b = 0, x = 1;
        bool first = false;
        for (int i = 0, j = slen - 1; i < slen; i++, j--) {
            a = (s[i] - 'a' + 1) + a * seed;
            b = b + (s[j] - 'a' + 1) * x;
            if (a == b) {
                if (first) printf(" ");
                else first = true;
                printf("%d", i + 1);
            }
            x *= seed;
        }
        printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值