Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Input: "A man, a plan, a canal: Panama"
Output: true
Input: "race a car"
Output: false
/*
* @lc app=leetcode id=125 lang=cpp
*
* [125] Valid Palindrome
*/
// @lc code=start
class Solution {
public:
bool isPalindrome(string s) {
for (int i = 0, j = s.length() - 1; i < j;) {
if (!isalpha(s[i]) && !isdigit(s[i])) {
++i;
} else if (!isalpha(s[j]) && !isdigit(s[j])) {
--j;
} else {
if (tolower(s[i]) != tolower(s[j])) {
return false;
}
++i;
--j;
}
}
return true;
}
};
// @lc code=end
class Solution {
public boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
char cl = s.charAt(l);
char cr = s.charAt(r);
if (!Character.isLetterOrDigit(cl)) {
l++;
} else if (!Character.isLetterOrDigit(cr)) {
r--;
} else if (Character.toLowerCase(cl) == Character.toLowerCase(cr)) {
l++;
r--;
} else {
return false;
}
}
return true;
}
}
时间复杂度O(n).