EasyLeetCode #125Two Pointers
Valid Palindrome
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.
Constraints
1 <= s.length <= 2 * 10^5, s consists only of printable ASCII characters
Examples
Input: s = "A man, a plan, a canal: Panama"
Output: true
Solution
Approach
Use two pointers from both ends. Skip non-alphanumeric characters and compare lowercase versions.
def isPalindrome(s):
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return TrueComplexity
Time:O(n)
Space:O(1)
Hints
- 1.Use two pointers from start and end
- 2.Skip non-alphanumeric characters
- 3.Compare lowercase versions
Asked at
Google