Given a string
s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Input: s = "race a car" Output: false Explanation: "raceacar" is not a palindrome.
1 <= s.length <= 2 * 105
sconsists only of printable ASCII characters.
A palindrome, and its reverse, are identical to each other.
class Solution: def isPalindrome(self, s: str) -> bool: s = s.lower() s_forward = "" s_backward = "" for c in s: if c.isalnum(): s_forward += c s_backward = c + s_backward return s_forward == s_backward
- Time complexity: O(N).
- Space complexity: O(N).