题目描述:给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
**说明:**本题中,我们将空字符串定义为有效的回文串。
eg:
示例 1:
输入: "A man, a plan, a canal: Panama"
输出: true
示例 2:
输入: "race a car"
输出: false思路描述:做今日的每日一题的时候就来做做这道题,其实蛮清晰的思路,使用两个指针分别指向首尾,如果遇到的字符是数字或字母就进行比较是否相等,如果不是的话就跳过去,因为题干中明显提出了只考虑字母和数字字符。
class Solution {
bool isNumOrChar(char c){
if(tolower(c) >= 'a' && tolower(c) <= 'z' || tolower(c) >= '0' && tolower(c) <= '9')
return true;
return false;
}
public:
bool isPalindrome(string s) {
int n = s.size();
if(n == 0) return true;
int low = 0, high = n - 1;
while(low < high){
if(!isNumOrChar(s[low])) low ++;
if(!isNumOrChar(s[high])) high --;
if(isNumOrChar(s[low]) && isNumOrChar(s[high])){
if(tolower(s[low]) == tolower(s[high])){
low ++; high --;
}else return false;
}
}
return true;
}
};