File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # 125. Valid Palindrome
2+ # Solution 1: Can early return False if chars don't match, so O(1) space.
3+ # Solution 2: Normalize the string first, then check if it's a palindrome. O(n) space for the normalized string.
4+
5+ class Solution :
6+ # Time Complexity: O(n)
7+ # Space Complexity: O(1)
8+ def isPalindrome (self , s : str ) -> bool :
9+ # Use two pointers from both ends
10+ left , right = 0 , len (s ) - 1
11+
12+ # Move inward from both ends, ignore non-alphanumeric chars
13+ # and compare chars case-insensitively.
14+ while left < right :
15+ while left < right and not s [left ].isalnum ():
16+ left += 1
17+ while left < right and not s [right ].isalnum ():
18+ right -= 1
19+ if s [left ].lower () != s [right ].lower ():
20+ return False
21+ left += 1
22+ right -= 1
23+ return True
24+
25+
26+ # Time Complexity: O(n)
27+ # Space Complexity: O(n)
28+ def isPalindrome2 (self , s :str ) -> bool :
29+ # Normalize the string by keeping only lowercase alphanumeric characters
30+ s = list (filter (str .isalnum , s .lower ()))
31+
32+ # Check if the list is the same forwards and backwards
33+ return s == s [::- 1 ]
You can’t perform that action at this time.
0 commit comments