给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
思路:
左右两边遍历
class Solution {
public:
bool isPalindrome(string s) {
int front = 0;
int rear = s.length()-1;
while(front < rear){
if(!isAlpha(s[front])){
front ++;
continue;
}
if(!isAlpha(s[rear])){
rear --;
continue;
}
if(low(s[front]) == low(s[rear])){
front ++;
rear --;
}else{
return false;
}
}
return true;
}
char low(char ch){
if(ch >= 'A' && ch <= 'Z') return 'a' + ch - 'A';
return ch;
}
bool isAlpha(char ch){
if(ch <= '9' && ch >= '0') return true;
if(ch >= 'a' && ch <= 'z') return true;
if(ch >= 'A' && ch <= 'Z') return true;
return false;
}
};