Skip to content

Commit 36176b9

Browse files
committed
valid palindrome solution
1 parent acc6d7e commit 36176b9

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

valid-palindrome/yerim01.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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

0 commit comments

Comments
 (0)