Problem statement
Solution
We solve this problem by verifying that the input string s reads the same forward and backward after ignoring non-alphanumeric characters and their case. The most direct way
to do this is with two pointers, one starting at the left and another starting at the
right.
The psuedocode for this solution is as follows:
- Set
l = 0andr = length(s) - 1. These are the two pointers. - While the left pointer
lis smaller than the right pointerr:
a. Ifs[l]is not an alphanumeric character, keep movinglto the right untils[l]is an alphanumeric character. Make sure thatl < rwhile doing this.
b. Ifs[r]is not an alphanumeric character, keep movingrto the left untils[r]is an alphanumeric character. Make sure thatl < rwhile doing this.
c. If the lowercase version ofs[l]is equal to the lowercase version ofs[r], then return movelto the right by1and moverto the left by1.
d. Otherwise, returnFalse, which means thatsis not a valid palindrome. - Return
True, which implies thatsis a valid palindrome.
In Python, this can be implemented as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
# Move the left pointer to the first alphanumeric
# character. We need to ensure that l < r so that
# the outer while loop's condition is also true.
while not s[l].isalnum() and l < r:
l += 1
# Move the right pointer to the first alphanumeric
# character. We need to ensure that l < r so that
# the outer while loop's condition is also true.
while not s[r].isalnum() and l < r:
r -= 1
if s[l].lower() == s[r].lower():
l += 1
r -= 1
else:
return False
return True
Let $n$ be the length of the input string s. Because
- every character is visited at most once by either pointer,
- skipped characters are processed in constant time, and
- each pointer only moves forward or backward,
this solution requires $O(n)$ time. Additionally, because only two integer variables
(the pointers) are used and there are no copies of the input string s, this solution
requires $O(1)$ space.