Problem:
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.
题意是判断一个字符串是否是回文字符串,也就是正序和逆序都是一样的字符串。题目要求仅仅判断字母和数字,并且不需要区分大小写。所以其他字符都是而已忽略的。题目比较简单,主要是从最左边和最右边对称比较,遇到其他字符就再移一位。算法复杂度在O(n),空间复杂度为O(1)。
Code:(LeetCode运行13ms)
class Solution {
public:
bool isPalindrome(string s) {
for (int left = 0, right = s.length() - 1; left < right; ) {
if (!::isalnum(s[left])) {
left++;
} else if (!::isalnum(s[right])) {
right--;
} else if (tolower(s[left]) != tolower(s[right])) {
return false;
} else {
left++;
right--;
}
}
return true;
}
};