Mike and palindrome

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;
        }
    }
}
全部评论

相关推荐

11-28 17:58
门头沟学院 Java
美团 JAVA开发 n×15.5
牛客786276759号:百度现在晋升很难的 而且云这块的业务没美团好 你看百度股价都跌成啥样了
点赞 评论 收藏
分享
实习挂完提前批挂_提前批挂完秋招挂:我是来结束这个秋招的😤
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务