統計句子中各種字元的出現次數
阿新 • • 發佈:2021-02-05
習題8-8 判斷迴文字串 (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
程式碼實現
方法一:
bool palindrome( char *s ){
bool result = true;
char *p1,*p2;
p1 = s;
p2 = s;
while(*p2!='\0'){
p2++;
}
p2--;//使指標指向字串結尾處
//printf("p1 = %c ,p2 = %c\n",*p1,*p2) ;
//從字串的首尾兩處開始移動指標,同時作比較
while(*p1!='\0'){
if(*p1!=*p2) result = false;
if(p2-p1<=0) break;
p1++;
p2--;
}
return result;
}
方法二:
/*呼叫strlen()函式直接求得字串的長度,和法一思路一樣,使用的工具不同*/
bool palindrome( char *s )
{
int i,cnt=strlen(s);
for(i=0;i<cnt/2;i++)
{
if(s[i]!=s[cnt-1-i])
break;
}
if(i==cnt/2)
return true;
else
return false;
}