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+ # Goal: Return true if it's a palindrome. If it's not, return false
2+ # - palindrome: a string that reads the same forward and backward
3+ # Time Complexity: O(n)
4+ # - Building string is O(n) + Two pointer check is O(n).
5+ # Space Complexity: O(n)
6+ # - We use a new string of size s.
7+ class Solution :
8+ def isPalindrome (self , s : str ) -> bool :
9+ chars = []
10+
11+ # Trim 's' to contain only alphanumerical characters
12+ for ch in s :
13+ if ch .isalnum ():
14+ chars .append (ch .lower ()) # make it case-insensitive
15+
16+ new_s = "" .join (chars )
17+
18+ # Use two pointers
19+ # ptr1 -> starting index ptr2 -> ending index
20+ ptr1 = 0
21+ ptr2 = len (new_s ) - 1
22+
23+ while ptr1 < ptr2 : # O(n) time
24+ # Return false if ptr1 and ptr2 point to different char
25+ if new_s [ptr1 ] != new_s [ptr2 ]:
26+ return False
27+ ptr1 += 1
28+ ptr2 -= 1
29+
30+ # Otherwise, return true
31+ return True
You can’t perform that action at this time.
0 commit comments