Skip to content

Commit 060958d

Browse files
committed
validate palindrome solutions
1 parent 6dfc9fc commit 060958d

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

valid-palindrome/dolphinflow86.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# 1) Iterate through the string using two-pointers, skipping non-alphanumeric characters and comparing them in lowercase to validate the palindrome in-place.
2+
# TC: O(N) where N is the length of s
3+
# SC: O(1)
4+
class Solution:
5+
def isPalindrome(self, s: str) -> bool:
6+
left = 0
7+
right = len(s) - 1
8+
9+
while left < right:
10+
if not s[left].isalnum():
11+
left += 1
12+
continue
13+
if not s[right].isalnum():
14+
right -= 1
15+
continue
16+
17+
if s[left].lower() != s[right].lower(): return False
18+
left += 1
19+
right -= 1
20+
21+
return True
22+
23+
# 2) Filter alphanumeric characters and conver them to lowercase to create a new string and then simply validate palindrome using two-pointers
24+
# TC: O(N) where N is the length of s
25+
# SC: O(N) where N is the length of s
26+
class Solution:
27+
def isPalindrome(self, s: str) -> bool:
28+
new_str = ""
29+
for ch in s:
30+
if ch.isalnum():
31+
new_str += ch.lower()
32+
33+
n = len(new_str)
34+
left = 0
35+
right = n - 1
36+
37+
while left < right:
38+
if new_str[left] != new_str[right]: return False
39+
left += 1
40+
right -= 1
41+
42+
return True

0 commit comments

Comments
 (0)