Skip to content

Commit 8b6e421

Browse files
committed
Add the second solution for Valid Palindrome problem.
1 parent f1772d1 commit 8b6e421

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

valid-palindrome/KwonNayeon.py

+29-6
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,40 @@
33
- 1 <= s.length <= 2 * 10^5
44
- s consists only of printable ASCII characters.
55
6-
Time Complexity:
7-
- O(n)
8-
Space Complexity:
9-
- O(n)
6+
<Solution 1>
7+
Time Complexity: O(n)
8+
9+
Space Complexity: O(n)
1010
"""
11-
# Solution 1
1211
class Solution:
1312
def isPalindrome(self, s: str) -> bool:
1413
s = re.sub(r'[^a-zA-z0-9]', '', s).lower()
1514
if s == s[::-1]:
1615
return True
1716
return False
17+
"""
18+
<Solution 2>
19+
Time Complexity: O(n)
20+
- 팰린드롬일 경우, 각 문자를 한 번씩 검사
21+
22+
Space Complexity: O(1)
23+
- left, right 포인터 외에 추가 공간 사용 없음
24+
"""
25+
class Solution:
26+
def isPalindrome(self, s: str) -> bool:
27+
left, right = 0, len(s) - 1
28+
29+
while left < right:
30+
while left < right and not s[left].isalnum():
31+
left += 1
32+
33+
while left < right and not s[right].isalnum():
34+
right -= 1
35+
36+
if s[left].lower() != s[right].lower():
37+
return False
38+
39+
left += 1
40+
right -= 1
1841

19-
# Solution 2
42+
return True

0 commit comments

Comments
 (0)