- Leetcode Learning System
- Posts
- Day 5 - Valid Palindrome
Day 5 - Valid Palindrome
π Problem:
A string is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward.
Given a string s, return True if itβs a valid palindrome, or False otherwise.
π§ͺ Examples:
Example 1
Input: s = "A man, a plan, a canal: Panama"
Output: True
Explanation: Becomes "amanaplanacanalpanama" β a palindrome.
Example 2
Input: s = "race a car"
Output: False
Explanation: "raceacar" is not the same forward and backward.
Example 3
Input: s = " "
Output: True
Explanation: After cleaning, the string is empty β which is considered a palindrome.
π Constraints:
1 <= s.length <= 2 Γ 10β΅sconsists only of printable ASCII characters
π§ How to Approach It
Step 1: Normalize the input
Convert everything to lowercase
Remove non-alphanumeric characters
You can use
isalnum()or a create a list of letters, and check if the char is in the list
Step 2: Check for symmetry
Use two pointers (
leftandright) to compare the string from both ends inward
β Python Solution:
class Solution:
def isPalindrome(self, s: str) -> bool:
s = ''.join(c.lower() for c in s if c.isalnum())
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
π§΅ TL;DR:
βοΈ Strip out anything that's not a letter or number
π Use two pointers to check if the string is symmetric
β‘ Efficient and clean β just like a good palindrome