125. Valid Palindrome
Difficulty: Easy
Topics: Two Pointers, String
Similar Questions:
Problem:
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
Solutions:
class Solution {
public:
bool isPalindrome(string s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
while (left < right && !isalphanum(s[left])) {
++left;
}
while (left < right && !std::isalnum(s[right])){ // remember the name of the funciton
--right;
}
if (s[left] >= '0' && s[left] <= '9' && s[left] != s[right]) {
return false;
}
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
++left;
--right;
}
return true;
}
bool isalphanum(char c) {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9';
}
};