回文判断,判断一段字符串中的数字和字母是否首尾一致,不区分大小写。
思路:
首先过滤掉其他字符,再分别判断首尾对应位置的字符是否相等,需要注意越界问题。
代码:(特殊测试数据“.,”)
bool isNumberOrLetter(char c){ //判断字符是否为数字或字母
if('0'<=c && c<='9')
{
return true;
}
else if('A'<=c && c<='Z')
{
return true;
}
else if('a'<=c && c<='z')
{
return true;
}
return false;
}
bool isPalindrome(string s) {
bool result=true;
int strLen=s.length();
int head=0,tail=strLen-1;
while(head<tail)
{
while(!isNumberOrLetter(s[head]) && head<tail) //注意判断head<tail,不然容易陷入死循环或者越界
{
head++;
}
while(!isNumberOrLetter(s[tail]) && head<tail)//注意判断head<tail,不然容易陷入死循环或者越界
{
tail--;
}
if(isNumberOrLetter(s[head]) && isNumberOrLetter(s[tail]) && tolower(s[head]) != tolower(s[tail]))
{ //先要判断两个字符是否有效再判断是否相等
result=false;
break;
}
head++;
tail--;
}
return result;
}
};
简单的一个题应为没有仔细考虑,导致错了很多遍,主要是对越界和死循环考虑不周。