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

相关推荐

机械打工仔:我来告诉你原因,是因为sobb有在线简历,有些HR为了快会直接先看在线简历,初步感觉不合适就不会找你要详细的了
投了多少份简历才上岸
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务