首页 > 解决方案 > 检查非对称回文

问题描述

我已经为 myprogramminglab 赋值编写了一个程序,它应该接受一个字符串输入,检查它是否是回文,然后输出结果。

我所拥有的是除了一项测试之外的所有工作。“一个人计划巴拿马运河”是一个回文,但我的程序说它不是。我认为这一定是因为程序将第二个空格与“巴拿马”中的“m”进行了比较。

另一方面,“我能在我看到厄尔巴岛”被捕获为回文,但我猜这是因为它是对称的,并且在左侧跳过一个空格与在左侧跳过一个空格同时发生正确的。

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

int is_not_alnum(char c);
int testPalindrome(const char string[], int begin, int end);


int main (void)
{
    int n;
    char temp;


    printf("Enter the size of your string: ");

    scanf("%d" , &n);

    char string[n];

    printf("Enter your string to check if it is a palindrome: ");
    scanf("%c",&temp);
    scanf("%[^\n]" , string);

    if(testPalindrome(string, 0 , n - 1))
        printf("\"%s\" is a Palindrome.\n" , string);
    else
        printf("\"%s\" is not a Palindrome.\n" , string);


    //puts("");

    return(0);
}

//program only needs to worry about lowercase and 0-9 alphanumeric
int is_not_alnum(char c)
{
    if( ((c >= 'a') && (c <= 'Z')) || ((c >= '0') && (c <= '9')) )
        return(0);
    else
        return(1);
}

int testPalindrome(const char string[], int begin, int end)
{
    while (begin <= end)
    {
    if(is_not_alnum(string[begin]))
        begin++;
    if(is_not_alnum(string[end]))
        end--;

    if(string[begin] == string[end])
    {
        return(testPalindrome(string , begin++ , end--));
        return(1);
    }
    else
        return(0);
    }
}

标签: c

解决方案


您正在检查大写字符“Z”,它应该是:

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

int is_not_alnum(char c);
int testPalindrome(const char string[], int begin, int end);


int main (void)
{
    int n;
    char temp;


    printf("Enter the size of your string: ");

    scanf("%d" , &n);

    char string[n];

    printf("Enter your string to check if it is a palindrome: ");
    scanf("%c",&temp);
    scanf("%[^\n]" , string);

    if(testPalindrome(string, 0 , n - 1))
        printf("\"%s\" is a Palindrome.\n" , string);
    else
        printf("\"%s\" is not a Palindrome.\n" , string);


    //puts("");

    return(0);
}

//program only needs to worry about lowercase and 0-9 alphanumeric
int is_not_alnum(char c)
{
    if( ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')) )
        return(0);
    else
        return(1);
}

int testPalindrome(const char string[], int begin, int end)
{
    if (begin <= end)
       return(1);

    if(is_not_alnum(string[begin]))
        begin++;
    if(is_not_alnum(string[end]))
        end--;

    if(string[begin] == string[end])
    {
        return(testPalindrome(string , begin++ , end--));
    }
    else
        return(0);

}

推荐阅读