power oj2610: 判断回文串(hash入门模板)

题目链接https://www.oj.swust.edu.cn:50443/problem/show/2610

Description

某天吃饭的时候,FM有了一个帅气idea,其实是个傻逼题?题意很简单,给一个字符串判断是否是回文串?
PS:如果一个字符串正着读和反着读都一样,那么这个字符串为回文串,比如aba,cc,cddc为回文串,而ac,acda,adA则不是回文串。

Input

多组输入,第一行为n,代表字符串的长度。第二行为这个字符串,该串仅包含大小写字母。

Output

是回文串输出"YES", 不是回文串输出 “NO”。

Sample Input

8
aaaaaaaa
7
tangcan
3
lyl

Sample Output

YES
NO
YES

Hint

回文串长度 1≤len≤107,请注意内存限制。Memory Limit: 4096 KB

正反求hash值即可

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
//#pragma GCC optimize(3,"Ofast","inline")
#define LL long long
//#define MT(a,b) memset(a,b,sizeof(a))
const int mod=1000007;
const int maxn=2e4+5;
const int ONF=-0x3f3f3f3f;
const int INF=0x3f3f3f3f;
unsigned LL Hash1,Hash2,p=233,P;
int main (){
    int n;
    char word;
    while (~scanf("%d",&n)){
        getchar();
        int mid=n>>1;
        Hash1=Hash2=0;
        for (int i=1;i<=mid;i++){
            word=getchar();
            Hash1=(Hash1*p+(unsigned LL)word)%mod;
        }
        if (n&1) getchar();
        P=1;
        for (int i=1;i<=mid;i++){
            word=getchar();
            Hash2=(Hash2+(unsigned LL)word*P)%mod;
            P=(P*p)%mod;
        }
        if (Hash1==Hash2) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值