简体   繁体   English

C语言中的回文字母缺失问题

[英]Palindrome Missing Alphabet issue in C

I wrote a code to find out the missing palindrome alphabet in a string. 我编写了一个代码,以找出字符串中缺少的回文字母。 It passes a few test cases and fails a few. 它通过了一些测试用例,但失败了。

I'm not sure where I made a mistake and everything seems right in the code. 我不确定我在哪里犯了错误,并且代码中的一切看起来都正确。

The code is, 代码是

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

int main()
{
    char palindromeChar[100];
    fgets(palindromeChar, 100, stdin);
    int revCtr = strlen(palindromeChar) - 1, fwdCtr = 0, counter;
    for(counter = 0; counter < strlen(palindromeChar)/2; counter++) {
        if(palindromeChar[fwdCtr] != palindromeChar[revCtr]) {
            printf("%c", palindromeChar[fwdCtr]);
            break;
        }
        ++fwdCtr;
        --revCtr;
    }

}

When it comes to inputs like, 当涉及到诸如

malayaam

It prints out, 它打印出来,

m

which is the first character in the case, but what the actual condition is if the forward character is not equal to the reverse character, it's asked to be print. 这是第一个字符,但是如果正向字符不等于反向字符,则实际情况是什么,要求打印该字符。

Why does it prints the first character itself? 为什么它会打印第一个字符本身? What's the problem and the fix? 有什么问题和解决方法?

Try printing {palindromeChar[revCtr]} as well, when you are using the break. 使用间隔时,也尝试打印{palindromeChar [revCtr]}。 It will help you to see the mismatched characters from front and end. 它将帮助您从前端和后端查看不匹配的字符。

fgets() includes the newline char '\\n' in the array, so you need to skip that character. fgets()在数组中包含换行符'\\ n',因此您需要跳过该字符。

int revCtr = strlen(palindromeChar) - 1

to

int revCtr = strlen(palindromeChar) - 2

Good point in the comment below about double checking for newline char first, so instead, leave revCtr as is and 在下面的注释中,关于先对换行符进行两次双重检查的要点,因此,请保留revCtr不变,并

    int revCtr = strlen(palindromeChar) - 1, fwdCtr = 0, counter;
    if (palindromeChar[revCtr] == '\n') {
        revCtr--;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM