给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1:
输入: "A man, a plan, a canal: Panama" 输出: true
示例 2:
输入: "race a car" 输出: false
class Solution {
public:
bool isPalindrome(string s) {
if(s.length()==0)
return true;
vector<char> ss;
for(int i=0;i<s.length();i++){
char t = s[i];
if(t >='A' && t<='Z')
t = t+32;
if(t >='a' && t <='z' || t >= '0' && t <= '9'){
ss.push_back(t);
}
}
for(int i = 0;i < ss.size()/2;i++){
if(ss[i] != ss[ss.size()-i-1])
return false;
}
return true;
}
};
另一个参考一个博主的:https://www.cnblogs.com/grandyang/p/4030114.html
class Solution {
public:
bool isPalindrome(string s) {
if(s.length()==0) return true;
int left = 0;
int right= s.size()-1;
while(left < right){
if(!isAlphNum(s[left]))
++left;
else if(!isAlphNum(s[right]))
--right;
else if ((s[left] + 32 - 'a') %32 != (s[right] + 32 - 'a') % 32) return false;
else {
++left;
--right;
}
}
return true;
}
bool isAlphNum(char &ch){
if (ch >='a' && ch <='z') return true;
if (ch >='A' && ch<='Z') return true;
if (ch >='0' && ch<='9') return true;
return false;
}
};