Valid Palindrome
- 1 min read
- String
- LC-Easy
Solution
- Two pointers, left and right
- While left is less than right:
- Increment left until an alphanumeric character is found and l < r
- Decrement right until an alphanumeric character is found and r > l
- If characters at pointers are not equal, return False
- If end of while loop reached, return true because the string was a palindrome
| Time | Space | Explanation |
|---|
O(n) | O(1) | |
def isPalindrome(self, s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum(): l += 1
while r > l and not s[r].isalnum(): r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True