Skip to content

Commit a4089d5

Browse files
committed
valid palindrome solution refactor
1 parent 909b6d7 commit a4089d5

1 file changed

Lines changed: 24 additions & 5 deletions

File tree

valid-palindrome/jylee2033.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,31 @@ def isPalindrome(self, s: str) -> bool:
33
# 1. Remove non-alphanumeric characters and convert to lowercase
44
# 2. Compare with reversed string
55

6-
cleaned_s = ""
7-
for ch in s:
8-
if ch.isalnum():
9-
cleaned_s += ch.lower()
6+
# cleaned_s = ""
7+
# for ch in s:
8+
# if ch.isalnum():
9+
# cleaned_s += ch.lower()
1010

11-
return cleaned_s == cleaned_s[::-1]
11+
# return cleaned_s == cleaned_s[::-1]
1212

1313
# Time Complexity : O(n)
1414
# Space Complexity : O(n)
15+
16+
left = 0
17+
right = len(s) - 1
18+
19+
while left < right:
20+
if not s[left].isalnum():
21+
left += 1
22+
elif not s[right].isalnum():
23+
right -= 1
24+
elif s[left].lower() != s[right].lower():
25+
return False
26+
else:
27+
left += 1
28+
right -= 1
29+
30+
return True
31+
32+
# Time Complexity : O(n)
33+
# Space Complexity : O(1)

0 commit comments

Comments
 (0)