判断字符串是否为回文
题目描述
输入一个字符串,输出该字符串是否回文。回文是指顺读和倒读都一样的字符串。
输入格式
输入一行字符串,长度小于 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";
}