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
trueif it is a palindrome, or
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.
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.
class Solution: def isPalindrome(self, s: str) -> bool: """ T: O(N) S: O(N) """ # Create a new list that only has letters and numbers values = [ch.lower() for ch in s if s.isalnum()] # Initialize two pointers a, b = 0, len(values) - 1 # Walk from the front and back to try to find a # pair that is not equal. Return False if such a # is found. while a < b: if values[a] != values[b]: return False a += 1 b -= 1 # The string is a valid palindrome. Return True return True