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.
class Solution:
def isPalindrome(self, s: str) -> bool:
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
elif s[i].lower() != s[j].lower():
return False
else:
i += 1
j -= 1
return True
class Solution {
public boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (!Character.isLetterOrDigit(s.charAt(i))) {
++i;
} else if (!Character.isLetterOrDigit(s.charAt(j))) {
--j;
} else if (Character.toUpperCase(s.charAt(i)) != Character.toUpperCase(s.charAt(j))) {
return false;
} else {
++i;
--j;
}
}
return true;
}
}
class Solution {
public:
bool isPalindrome(string s) {
int i = 0, j = s.size() - 1;
while (i < j) {
if (!isAlphaNum(s[i])) ++i;
else if (!isAlphaNum(s[j])) --j;
else if ((s[i] + 32 - 'a') % 32 != (s[j] + 32 - 'a') % 32) return false;
else {
++i;
--j;
}
}
return true;
}
private:
bool isAlphaNum(char &ch) {
if (ch >= 'a' && ch <= 'z') return true;
if (ch >= 'A' && ch <= 'Z') return true;
if (ch >= '0' && ch <= '9') return true;
return false;
}
};
function isPalindrome(s: string): boolean {
let left: number = 0,
right: number = s.length - 1;
while (left < right) {
let char1: string = s.charAt(left);
let char2: string = s.charAt(right);
if (!/[a-zA-Z0-9]/.test(char1)) {
++left;
} else if (!/[a-zA-Z0-9]/.test(char2)) {
--right;
} else if (char1.toLocaleLowerCase() != char2.toLocaleLowerCase()) {
return false;
} else {
++left;
--right;
}
}
return true;
}