————————————————————————————————————
⏩ 大家好哇!我是小光,嵌入式爱好者,一个想要成为系统架构师的大三学生。
⏩最近在准备秋招,一直在练习编程。
⏩本篇文章对赛码网的回文串 题目做一个详解。
⏩感谢你的阅读,不对的地方欢迎指正。
————————————————————————————————————
题目:
思路解析:
- 题目要求判断给定的字符串能否通过添加一个字母,变成回文串。
- 回文串的特点是正着和反着读都一样,那么我们可以通过比较字符串与其反转后的字符串是否相等来判断是否是回文串。
- 如果该字符串本身已经是回文串了,直接返回"Yes"。
- 需要判断首部与尾部的对称字符是否相等,如果相等,则添加字母后可以得到一个回文串;如果不相等,则无法通过添加一个字母得到回文串。
- 根据上述条件进行判断,如果满足则返回"Yes",否则返回"No"。
具体实现步骤:
- 判断字符串本身是否为回文串,如果是,则直接返回"Yes"。 如果字符串不是回文串,遍历字符串的每个位置,将一个字母插入到该位置作为测试。
- 对于每个位置,判断插入字母后的字符串是否变成了回文串。
- 如果存在至少一个位置满足添加字母后变成回文串的条件,返回"Yes";否则返回"No"。
代码如下:
#include <stdio.h>
#include <string.h>
int isPalindrome(char *s) {//判断字符串是否回文
int length = strlen(s);
for (int i = 0; i < length / 2; i++) {
if (s[i] != s[length - i - 1]) {
return 0;
}
}
return 1;
}
int canBePalindrome(char *s,char c) {//判断在任意位置加入c字符后字符串是否回文
if (isPalindrome(s)) {
return 1;
}
int length = strlen(s);
for (int i = 0; i <= length; i++) {
char temp[12];
strncpy(temp, s, i);
temp[i] = c; // 添加一个字母
strncpy(temp + i + 1, s + i, length - i);
temp[length + 1] = '\0';
if (isPalindrome(temp)) {
return 1;
}
}
return 0;
}
int canBehuiwen(char *s)//判断加入a-z字符后字符是否回文
{
for(char c = 'a';c <= 'z';c++){
if(canBePalindrome(s,c)) return 1;
}
return 0;
}
int main() {
char s[11];
scanf("%s", s);
if (canBehuiwen(s)) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}