特别注意:
1. 单个字符也是回文,例如 “a”
2. 字符和数字都是有效的,例如 “1a1”是回文
#include <stdio.h>
#include <stdbool.h>
bool isValidIndex(int ulHead, int ulTail, const int LEN)
{
if(ulHead < ulTail && ulHead < LEN && ulHead >= 0 && ulTail < LEN && ulTail >= 0)
return true;
else
return false;
}
bool isValidChar(char ucLetter)
{
if((ucLetter >= 'A' && ucLetter <= 'Z')
|| (ucLetter >= 'a' && ucLetter <= 'z')
|| (ucLetter >= '0' && ucLetter <= '9'))
return true;
else
return false;
}
bool isSame(char ucHead, char ucTail)
{
/*定义局部变量*/
char cmpHead;
char cmpTail;
/*非字母则退出*/
if( (!isValidChar(ucHead)) || (!isValidChar(ucTail)) )
return false;
/*字符转换为小写*/
if(ucHead >= 'A' && ucHead <= 'Z')
cmpHead = ucHead-'A'+'a';
else
cmpHead = ucHead;
if(ucTail >= 'A' && ucTail <= 'Z')
cmpTail = ucTail-'A'+'a';
else
cmpTail = ucTail;
/*比较字符*/
if(cmpHead == cmpTail)
return true;
else
return false;
}
bool isPalindrome(char* s)
{
/*空字符串为回文字符串*/
if(s == 0 || strlen(s) == 0 || strlen(s) == 1)
return true;
/*定义局部变量*/
int ulHead = 0;
int ulTail = strlen(s) - 1;
const int LEN = strlen(s);
bool result = true;
while(isValidIndex(ulHead,ulTail,LEN))
{
if(!isValidChar(s[ulHead]))
{
ulHead++;
continue;
}
if(!isValidChar(s[ulTail]))
{
ulTail--;
continue;
}
/*判断字符是否相等*/
if( !isSame(s[ulHead], s[ulTail]) )
{
result = false;
break;
}
else
{
ulHead++;
ulTail--;
}
}
return result;
}
int main()
{
char *s = "1r 1";
int result = isPalindrome(s);
printf("%d\n", result);
}