So my solution is setting two pointers
right, and make them move toward each other. Both of them would skip unimportant characters like '?'. A valid palindrome would make
s[left] == s[right] in every step.
from string import punctuation def isPalindrome(self, s): skip_items = set(punctuation) skip_items.add(' ') left, right = 0, len(s) - 1 while left < right: # Skip the unimportant chars while s[left] in skip_items: left += 1 if left == right: return True while s[right] in skip_items: right -= 1 if left == right: return True # Compare the left and the right if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True
A much easier and more pythonic solution is here, which uses
filter() and reversed comparison.