直接讀一整個字串時,需要把最後面的 '\n' 換成 '\0',使用 strlen 才會是預期的。
分兩個部分 check:
palindrome:
單純檢查左右是否對稱。
mirrored string:
單純檢查對面的是否是自己的 reverse。若是奇數個,中間的要 reverse 回自己。
分開檢查程式在撰寫時會比較單純。
最後要注意的是:檢查表格的轉換有沒有對照錯誤或漏掉。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char rever(char c){
switch(c){
case 'A':
return 'A';
case 'E':
return '3';
case 'H':
return 'H';
case 'I':
return 'I';
case 'J':
return 'L';
case 'L':
return 'J';
case 'M':
return 'M';
case 'O':
return 'O';
case 'S':
return '2';
case 'T':
return 'T';
case 'U':
return 'U';
case 'V':
return 'V';
case 'W':
return 'W';
case 'X':
return 'X';
case 'Y':
return 'Y';
case 'Z':
return '5';
case '1':
return '1';
case '2':
return 'S';
case '3':
return 'E';
case '5':
return 'Z';
case '8':
return '8';
default:
return 0;
}
}
int main(void){
char buf[50];
int m,p,i,j;
while(fgets(buf,50-1,stdin)!=NULL){
buf[strlen(buf)-1]='\0';
m=p=0;
for(i=0,j=strlen(buf)-1;i<=strlen(buf)/2;i++,j--){
if(buf[i]!=buf[j])
break;
}
if(i>strlen(buf)/2)
p=1;
for(i=0,j=strlen(buf)-1;i<=strlen(buf)/2;i++,j--){
if(rever(buf[i])==NULL || rever(buf[j])==NULL)
break;
if(rever(buf[i])!=buf[j])
break;
}
if(i>strlen(buf)/2)
m=1;
printf("%s",buf);
if(m==1&&p==1){
printf(" -- is a mirrored palindrome.\n\n");
}else if(p==1){
printf(" -- is a regular palindrome.\n\n");
}else if(m==1){
printf(" -- is a mirrored string.\n\n");
}else{
printf(" -- is not a palindrome.\n\n");
}
}
return 0;
}
沒有留言:
張貼留言