美文网首页
Mike and palindrome

Mike and palindrome

作者: Chilkings | 来源:发表于2019-05-10 12:05 被阅读0次

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.

image.png
题目大意:
判断输入的字符串能否通过修改一个字符变成回文字符
输出 YES or NO
PS:
字符长度为偶数时,输入回文字符串,应判断为NO
字符长度为奇数时,输入回文字符串,应判断为YES
因为中间那个字符可以随便改!!!

超简洁写法

#include <stdio.h>
#include <string.h>

int main() 
{
    char s[25];
    scanf("%s",s);
    int n,count=0;
    n = strlen(s);
    for(int i=0;i<n/2;i++)
    {
        if(s[i]!=s[n-i-1])
            count++;
    }
    printf("%s\n",(count==1||(count==0&&n%2==1))?"YES":"NO");
    return 0;
}

常规写法

#include<stdio.h>
#include<string.h>

void judge (char *s,int n)
{
    int i,m=0;
    for(i=0;i<n/2;i++)
    {
        if(s[i]!=s[n-1-i])
            m++;
    }
    if(n%2==1&&m==0)
        printf("YES\n");
    /*是当字符串长度是奇数并且本身就是回文字符串(没有不匹配字符)时,
    可以通过改变中间字符,达到必须更改一个字符的要求。*/
    else
    {
        if(m==1)
/*当字符串长度为偶数时,本身是回文数是无法通过修改一个字符变成回文数的*/
        {
            printf("YES\n");
        }
        else
        {
                printf("NO\n");
        }
    }
}

int main()
{
    char s[25];
    int n=0;
    memset(s,0,sizeof(s));
    scanf("%s",s);
    n = strlen(s);
    judge(s,n);
    return 0;
}

相关文章

网友评论

      本文标题:Mike and palindrome

      本文链接:https://www.haomeiwen.com/subject/vzhmvqtx.html