Mike and palindrome

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
因为中间那个字符可以随便改!!!

超简洁写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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;
}

常规写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#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;
}

坚持技术分享,如果帮助到了您,您的支持将鼓励我继续创作!