LeetCode 125. Valid Palindrome
Given a string s
, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.
Constraints:
1 <= s.length <= 2 * 105
s
consists only of printable ASCII characters.
Solution
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.length() - 1;
while (i < j) {
while (!isalpha(s[i]) && !isdigit(s[i]) && i <= j) {
i++;
}
while (!isalpha(s[j]) && !isdigit(s[j]) && i <= j) {
j--;
}
if (i >= j) {
break;
}
if (toupper(s[i]) != toupper(s[j])) {
return false;
}
i++;
j--;
}
return true;
}
};
PreviousLeetCode 124. Binary Tree Maximum Path SumNextLeetCode 153. Find Minimum in Rotated Sorted Array
Last updated
Was this helpful?