Description
Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings “z”, “aaa”, “aba”, “abccba” are palindromes, but strings “codeforces”, “reality”, “ab” are not.
Input
The first and single line contains string s (1 ≤ |s| ≤ 15).
Output
Print “YES” (without quotes) if Mike can change exactly one character so that the resulting string is palindrome or “NO” (without quotes) otherwise.
Examples
Input
abccaa
Output
YES
Input
abbcca
Output
NO
Input
abcda
Output
YES
题解:因为给了字符串是回文字符串,所以只要扫一遍,然后统计不同字符数量就行。
有一个小坑,就是当字符串长度是奇数并且本身就是回文字符串(没有不匹配字符)时,可以通过改变中间字符,达到必须更改一个字符的要求。
C语言版本一
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char a[20];
scanf("%s",&a);
int i;
int count=0;
for(i=0;i<strlen(a)/2;i++){
if(a[i]!=a[strlen(a)-1-i]) count++;
}
if(count==0&&strlen(a)%2==1||count==1) printf("YES\n");
else printf("NO\n");
return 0;
}
C++版本一
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
string s;
cin>>s;
int n=s.size(),count=0;
for(int i=0;i<n/2;i++)
{
if(s[i]!=s[n-i-1])
count++;
}
cout<<((count==1||(count==0&&n%2==1))?"YES":"NO")<<endl;
return 0;
}
C++版本二
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
while(cin>>s)
{
int len=s.length();
int cnt=0;
if(len<=1) {cout<<"YES"<<endl;continue;}
for(int i=0,j=len-1;i<len/2;i++,j--)
{
if(cnt>1) break;
if(s[i]!=s[j]) cnt++;
}
if((len%2)&&(cnt==0)) cnt++;
if(cnt==1) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
C++版本三
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[20];
int i,l,j;
while(cin>>str)
{
j=0;
l=strlen(str);
for(i=0;i<l/2;i++)
{
if(str[i]==str[l-i-1])
j++;
}
if(l%2==1)
{
if(j==l/2||j==l/2-1)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
else
{
if(j==l/2-1)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
}