问题描述
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama" Output: true
Example 2:
Input: "race a car" Output: false
代码实现
#include <cctype>
using std::isalnum;
using std::isupper;
using std::tolower;
class Solution {
public:
bool isPalindrome(string s) {
int n = s.size();
int i = 0;
int j = n - 1;
while (i < j) {
if (!isalnum(s[i])) {
++i;
} else if (!isalnum(s[j])) {
--j;
} else if (isupper(s[i])) {
s[i] = tolower(s[i]);
} else if (isupper(s[j])) {
s[j] = tolower(s[j]);
} else if (s[i] != s[j]) {
return false;
} else {
++i;
--j;
}
}
return true;
}
};