Skip to content

Commit eedb8e6

Browse files
committed
feat: add valid-palindrome solution
1 parent 8e3b29e commit eedb8e6

File tree

1 file changed

+48
-4
lines changed

1 file changed

+48
-4
lines changed

valid-palindrome/shinsj4653.py

+48-4
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,57 @@
11
"""
22
[문제풀이]
33
# Inputs
4-
4+
- string s
55
# Outputs
6-
6+
- palindrome 인지에 대한 true, false 여부
77
# Constraints
8-
8+
- 1 <= s.length <= 2 * 10^5
9+
- s consists only of printable ASCII characters.
910
# Ideas
11+
문자열 최대 길이 10^5 -> 2중 for문 불가능
12+
13+
우선 s를 순회하며,
14+
- isalpha인 요소라면 lower 화 시켜서 새로운 문자열 p 에 붙이기
15+
- 그리고 그 p가 p == p[::-1] 이면 true, 아니면 false
16+
17+
TC: O(n), SC: O(n)
1018
1119
[회고]
20+
문제 조건에 all non-alphanumeric characters를 제외한 문자열을 기준으로
21+
-> 즉, numeric도 고려해야한다!
22+
23+
너무 쉬운 해결방법인 [::-1]를 쓴 것 같아서,
24+
해설 참고
25+
-> 투 포인터
26+
27+
"""
28+
29+
class Solution:
30+
def isPalindrome(self, s: str) -> bool:
31+
t = ""
32+
33+
for c in s:
34+
if c.isalpha():
35+
t += c.lower()
36+
elif c.isalnum():
37+
t += c
38+
39+
return t == t[::-1]
40+
41+
# 해설: 투 포인터 풀이
42+
class Solution:
43+
def isPalindrome(s):
44+
low, high = 0, len(s) - 1
45+
while low < high:
46+
while low < high and not s[low].isalnum():
47+
low += 1
48+
while low < high and not s[high].isalnum():
49+
high -= 1
50+
if s[low].lower() != s[high].lower():
51+
return False
52+
low, high = low + 1, high - 1
53+
return True
54+
55+
isPalindrome("A man, a plan, a canal: Panama")
56+
1257

13-
"""

0 commit comments

Comments
 (0)