Palindromization
Mihahim has a string s. He wants to delete exactly one character from it so that the resulting string would be a palindrome. Determine if he can do it, and if he can, what character should be deleted.
Input
The input contains a string s of length (2 ≤ |s| ≤ 200000), consisting of lowercase Latin letters.
Output
If the solution exists, output «YES» (without quotes) in the first line. Then in the second line output a single integer x — the number of the character that should be removed from s so that the resulting string would be a palindrome. The characters in the string are numbered from 1. If there are several possible solutions, output any of them.
If the solution doesn’t exist, output «NO» (without quotes).
Examples
input
evertree
output
YES
2
input
emerald
output
NO
input
aa
output
YES
2
题意:给你一个字符串,去掉一个字符,能否使其变成回文串。
分析:只去掉一个字符,所以可从头尾两端开始匹配,遇到不一样的就有两种可能,左边右移一位还是右边左移一位两种情况。还有就是一开始就是回文串的。直接模拟就行了
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f3f;
string s;
int place;
void judge2(int left,int right,int &cnt){
int l=(right-left+1)/2;
for (int i=0;i<l;i++){
if (s[left+i]!=s[right-i]){
cnt++;
break;
}
}
}
int judge (string s,int len,int &cnt){
int left=0,right=len-1;
for (int i=0;i<len/2;i++){
if (s[i+left]!=s[len-1-i]) {
judge2(i+left+1,len-1-i,++cnt);
place=i+left;
if (cnt==1)break;
cnt=1;
judge2(i+left,len-1-i-1,cnt);
place=len-i-1;
break;
}
}
}
int main ()
{
while (cin>>s){
int len=s.length();
if (len==2) {//如果长度为2,肯定可以,随便去除一个字符
printf ("YES\n");
printf ("1\n");
continue;
}
if (len==3){//长度为三的有三种可能
if (s[0]==s[1]) printf ("YES\n3\n");
else if (s[1]==s[2])printf ("YES\n1\n");
else if (s[0]==s[2])printf ("YES\n2\n");
else printf ("NO\n");
continue;
}
int cnt=0;
judge(s,len,cnt);
if (cnt==2){
printf ("NO\n");
}
else if (cnt==1){
printf ("YES\n");
printf ("%d\n",place+1);
}
else if (cnt==0){//一开始就是回文串
printf ("YES\n%d\n",len/2+1);
}
return 0;
}