LeetMotion
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.
s consists only of printable ASCII characters.Filter out all non-alphanumeric characters, lowercase the result, then check if it equals its own reverse. Simple but uses O(n) extra space.
filtered == filtered[::-1].Why it's not optimal: Allocates an O(n) filtered string and another O(n) for the reversed copy. The two-pointer approach avoids this with O(1) space.
def isPalindrome(s): filtered = "".join(c.lower() for c in s if c.isalnum()) return filtered == filtered[::-1]
We can eliminate the need for creating a new filtered string by using two pointers starting from the ends of the original string. This uses O(1) space memory!
l = 0 and r = len(s) - 1.l < r, gracefully skip any non-alphanumeric characters by moving l++ or r--.s[l].lower() == s[r].lower().False immediately.
Discussion
…