1. 程式人生 > >判斷迴文字串 (20 分)c語言解答(指標法)

判斷迴文字串 (20 分)c語言解答(指標法)

判斷迴文字串 (20 分)

本題要求編寫函式,判斷給定的一串字元是否為“迴文”。所謂“迴文”是指順讀和倒讀都一樣的字串。如“XYZYX”和“xyzzyx”都是迴文。

函式介面定義:

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

    scanf("%s", s);
    if ( palindrome(s)==true )
        printf("Yes\n");
    else
        printf("No\n");
    printf("%s\n", s);

    return 0;
}

/* 你的程式碼將被嵌在這裡 */

輸入樣例1:

thisistrueurtsisiht
輸出樣例1:

Yes
thisistrueurtsisiht
輸入樣例2:

thisisnottrue
輸出樣例2:

No
thisisnottrue

我的程式碼

#include<stdio.h>
#include<string.h>
bool palindrome( char *s ){
	//指標法
	char* p;//指向字串第一個元素的指標
	char* q;//指向最後一個字元的指標
	p=s;
	q=s+strlen(s)-1;
	while(p<q){
		if(*p!=*q){
			return false;
		}
		p++;
		q--;
	}	
	return true; 
}
/*也可以這麼寫*/
/* if(*p++!=*q--) */