B2124 判断字符串是否为回文(哈希字符串做法

判断字符串是否为回文

题目描述

输入一个字符串,输出该字符串是否回文。回文是指顺读和倒读都一样的字符串。

输入格式

输入一行字符串,长度小于 100 100 100

输出格式

如果字符串是回文,输出 yes;否则,输出 no

样例 #1

样例输入 #1

abcdedcba

样例输出 #1

yes

做法一,逐个判断(没事找事)

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
using LL = long long; 
LL h[N], p[N];
const int P = 131;
const LL MOD = 20000007; 

int get(int l,int r){
    return ((h[r]-h[l-1]*p[r-l+1])%MOD+MOD)%MOD;
}

int main() {
	string s;cin>>s;
	p[0]=1;
	for(int i=0,j=1;i<s.size();j++,i++){
		h[j]=(h[j-1]*P+s[i])%MOD;
		p[j]=(p[j-1]*P)%MOD;
	} 
	bool fl=true;
	for(int i=1,j=s.size();i<j&&fl;i++,j--){
	    if(get(i,i)==get(j,j))continue;
	    fl=false;
	}
	if(fl)cout<<"yes";
	else cout<<"no";
}

做法二:翻转后的哈希与原哈希判断(也是闲得蛋疼)

#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
using LL = long long; 
LL h1[N],h2[N], p[N];
const int P = 131;
const LL MOD = 20000007; 

LL get(int t,int l,int r){
    if(t==1)return ((h1[r]-h1[l-1]*p[r-l+1])%MOD+MOD)%MOD;
    else return ((h2[r]-h2[l-1]*p[r-l+1])%MOD+MOD)%MOD;
}



int main() {
	string s;cin>>s;
	p[0]=1;
	for(int i=0,j=1,k=s.size();i<s.size();j++,i++,k--){
		h1[j]=(h1[j-1]*P+s[i])%MOD;
		h2[j]=(h2[j-1]*P+s[k-1])%MOD; 
		p[j]=(p[j-1]*P)%MOD;
		
	} 
	bool fl=true;
	for(int i=1;i<s.size()&&fl;i++){
	    if(get(1,1,i)==get(2,1,i))continue;
	    fl=false;
	}
	if(fl)cout<<"yes";
	else cout<<"no";
}
  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值