-1

I'm checking the palindrome using the stack. I want to receive input from the user, determine whether it is a palindrome, and output the result

I want to ignore it without using a method of removing spaces and special characters, but it doesn't go as I want.

The code is

//
int palindrome(char string[])
{
    Stack s;

    int ii;

    initStack(&s);

    for (ii = 0; string[ii] != '\0'; ii++)
    {
        if (string[ii] >= 'A' && string[ii] <= 'Z')
            string[ii] += 32;

        if (string[ii] >= 'a' && string[ii] <= 'z')
        {
            push(&s, string[ii]);

        }
    }
    //printf("%s\n", string);
    for (ii = 0; string[ii] != 0; ii++)
    {
        if (string[ii] != pop(&s))
        {
            return 0;
        }

    }
    return 1;
}
int main()
{

    char string[MAX_STACK_SIZE];

    printf("Enter a String\n");
    gets_s(string);

    if (palindrome(string))
        printf("palindrome!\n");
    else
        printf("X\n");



    return 0;
}

In this part, the range between 'a' and 'z' was specified, and I wonder why special characters and spaces are not excluded and pushed into the stack.

    for (ii = 0; string[ii] != '\0'; ii++)
    {
        if (string[ii] >= 'A' && string[ii] <= 'Z')
            string[ii] += 32;

        if (string[ii] >= 'a' && string[ii] <= 'z')
        {
            push(&s, string[ii]);

        }
    }

1 Answers1

3

The problem is this for loop

for (ii = 0; string[ii] != 0; ii++)
{
    if (string[ii] != pop(&s))
    {
        return 0;
    }

}

where you are not skipping special characters in the source string.

Pay attention to that the source string should not be changed within the function. Also do not use magic numbers like 32. Use standard C functions isalpha and tolower.

The function can look for example the following way

#include <ctype.h>

//...

int palindrome( const char string[] )
{
    Stack s;
    initStack( &s );

    for ( const char *p = string; *p != '\0'; ++p )
    {
        char c = *p;

        if ( isalpha( ( unsigned char )c ) )
        {
            c = tolower( ( unsigned char )c );  
            push( &s, c );
        }
    }

    int equal = 1;

    for ( const char *p = string; equal && *p != '\0'; ++p )
    {
        char c = *p;
    
        if ( isalpha( ( unsigned char )c ) )
        {
            c = tolower( ( unsigned char )c );
            equal = c == pop( &s );
        }
    }

    return equal;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335