简体   繁体   English

使用堆栈检查给定字符串是否为回文

[英]check whether the given string is palindrome using stack

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.在这部分中,指定了 'a' 和 'z' 之间的范围,我想知道为什么不排除特殊字符和空格并将其压入堆栈。

    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]);

        }
    }

The problem is this for loop问题是这个 for 循环

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 .也不要使用像32这样的幻数。 Use standard C functions isalpha and tolower .使用标准 C 函数isalphatolower

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;
}

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

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