您的位置:首页 > 其它

Valid Palindrome 判断回文字符串

2015-06-13 12:02 232 查看
特别注意:

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: