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. Given a string s, return true if it is a palindrome, or false otherwise.
- Input: A string
s. - Output:
trueifsis a palindrome,falseotherwise. - Constraints:
1 <= s.length <= 2 * 10^5sconsists only of printable ASCII characters.
- Example:
Input: s = "A man, a plan, a canal: Panama" Output: true Explanation: "amanaplanacanalpanama" is a palindrome.
Solution
The most efficient way to check for a palindrome is using a two-pointer approach.
- Preprocessing: First, create a new string or process the original string such that only alphanumeric characters remain and all characters are converted to lowercase. This simplifies comparison.
- Two Pointers: Initialize two pointers,
leftat the beginning andrightat the end of the processed string. - Comparison: Move
leftforward andrightbackward, comparing characters at each position.- If
processed_string[left]is not equal toprocessed_string[right]at any point, the string is not a palindrome, so returnfalse. - Continue this process until
leftcrossesright.
- If
- Result: If the loop completes without finding any mismatches, the string is a palindrome, so return
true.
class Solution:
def isPalindrome(self, s: str) -> bool:
# Preprocess the string: convert to lowercase and remove non-alphanumeric characters
# Using a list comprehension for clarity and performance
filtered_chars = [char.lower() for char in s if char.isalnum()]
processed_s = "".join(filtered_chars)
# Use two pointers
left, right = 0, len(processed_s) - 1
while left < right:
if processed_s[left] != processed_s[right]:
return False
left += 1
right -= 1
return True
