以下是我编写的用于查找字符串回文中缺失字符的代码,但我不知道如何在同时从两边检查字符串的同时找到必须打印的字符。
#include <stdio.h>
#include <stdlib.h>
int main() {
char s[100], m[100];
fgets(s, 100, stdin);
int len = strlen(s);
int a, b;
for (int i = 0; i < strlen(s); i++) {
m[i] = s[len - i - 1];
}
for (int i = 0, j = 0; i <= strlen(s), j <= strlen(s); i++, j++) {
if (isspace(m[j])) {
j++;
}
if (s[i] != m[j]) {
if (len % 2 == 0) {
printf("%c", m[j]);
break;
} else {
printf("%c", s[i]);
break;
}
}
}
}
输入:马来亚语
输出:l
输入:abcddcb
输出:a
最佳答案
假设回文中总是恰好有一个错误,我建议查看每边的下一个字母,以确定两个不相同的字母中哪一个是缺失的。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char s[100],m[100];
fgets(s,100,stdin);
int len=strlen(s)-1;
int i,j;
for(i=0;i<len;i++)
{
m[i]=tolower((unsigned char)s[len-i-1]);
s[i]=tolower((unsigned char)s[i]);
}
for(i=0,j=0;i<len;i++,j++)
{
if(s[i]!=m[j])
{
printf("%c != %c, ", s[i], m[j]);
if(s[i+1]==m[j])
{ printf("but %c == %c, %c should be inserted on the right.\n", s[i+1], m[j], s[i]);
} else if(s[i]==m[j+1])
{ printf("but %c == %c, %c should be inserted on the left.\n", s[i], m[j+1], m[j]);
} else
{ printf("giving up.\n");
}
break;
}
}
return 0;
}
注意:
- 我合并了 mch 以及后来的 chqrlie 和 chux 的评论
- 我添加了所有输入的小写字母,以防止“Malayaam”中出现“m”!="M"
- 我认为您的 [mcve] 不完整,所以我编辑了一些内容。
- 为了向后兼容旧的 C,我做了一些编辑
(例如,在 for 循环头中没有声明i
)。 - 恰好一个错误的假设避免了一些边缘情况
关于c - 在字符串回文中找到缺失的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45897660/