题目:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
题意:
给定一个字符串,只考虑数字跟字母,并且忽略字母的大小写,判断这个字符串是否是回文串。
思路:
需要两个指针,一个从前往后,一个从后往前。如果遇到非数字非字母那么直接移动,如果是数字或者字母,则需要判断数字是否相等,字母在不考虑大小写的情况下是否相等。
以上。
代码如下:
class Solution {
public:
bool isPalindrome(string s) {
if(s.length() == 0)return true;
int i = 0, j = s.length() - 1;
while(i < j){
if(!isValid(s[i])) {
i++;
continue;
}
if(!isValid(s[j])) {
j--;
continue;
}
if(!isEqual(s[i], s[j]))return false;
else {
i++;
j--;
}
}
return true;
}
bool isValid(char c){
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))return true;
return false;
}
bool isEqual(char a, char b){
if((a == b) || (a >= 'A' && (a - b == 32) || (a - b == -32)))return true;
return false;
}
};