Problem Statement
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
, returntrue
if it is a palindrome, orfalse
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.
Solution
Python
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