125. Valid Palindrome
Question
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s , return true if it is a palindrome , or false otherwise .
Example 1:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " " Output: true Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
Constraints:
1 <= s.length <= 2 * 10 5sconsists only of printable ASCII characters.
Solutions
bool isPalindrome(string s) {
// two pointer approach:
// use left and right pointer from two side of the the string
// left go to right side and find char that is alnum
// right go to left side and find char that is alnum
// compare them. if not equal , return false;
// Edge cases:
// 1. when string is "" -> directly return true
// 2. when string is "a" any alnum -> handled by the while loop
// 3. when string is not any alnum -> handled by the while loop
// Time Complexity: O(N)
// Space Complexity: O(1)
int n = static_cast<int>(s.size());
int left = 0;
int right = n - 1;
while (left < right) {
while (left < right && !isalnum(static_cast<char>(s[left])))
++left;
while (left < right && !isalnum(static_cast<char>(s[right])))
--right;
if (left < right) {
if (tolower(s[left]) != tolower(s[right])) {
return false;
}
++left;
--right;
}
}
return true;
}