6-3 判断回文字符串(20 分)

函数接口定义:

bool palindrome( char *s );
函数palindrome判断输入字符串char *s是否为回文。若是则返回true,否则返回false。

题目代码

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

#define MAXN 20
typedef enum {false, true} bool;

bool palindrome( char *s );

int main()
{
    //调试:char s[MAXN]="thisistrueurtsisiht";
    char s[MAXN];
    scanf("%s", s);
    if ( palindrome(s) == true )
        printf("Yes\n");
    else
        printf("No\n");
    printf("%s\n", s);

    return 0;
}

bool palindrome( char *s ){
    //调试:printf("get:%s\n", s);
    bool isPalindrome=false;
    char *head = s;
    char *tail = s+strlen(s)-1;
    while( *head == *tail ){
        if( head >= tail ){
            break;
        }
        else{
            head++;
            tail--;
        }
    }
    // 调试:printf("head-tail=%d\n", head-tail);
    if( (strlen(s)%2==0 && head-tail==1) || (strlen(s)%2==1 && head-tail==0) ){
        isPalindrome = true; // 按传入的字符串长度的奇偶性分两种结果判断
    }
    else{
        isPalindrome = false;
    }
    return isPalindrome;
}


猜你喜欢

转载自blog.csdn.net/qq_36913610/article/details/81037803