Skip to content

Commit e92eb77

Browse files
committed
leetcode - 125
1 parent d9464aa commit e92eb77

File tree

1 file changed

+47
-15
lines changed

1 file changed

+47
-15
lines changed

python/string/leetcode_125.py

Lines changed: 47 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,54 @@
22
# 125. Valid Palindrome
33
# https://leetcode.com/problems/valid-palindrome/
44

5-
class Solution:
6-
def isPalindrome(self, s: str) -> bool:
5+
import collections
6+
import re
77

8-
# 나라면 대문자를 모두 소문자로 바꾼 다음에, 문자가 아닌 것들을 전부 제거할 것 같습니다.
9-
# 1. 문자만 놔둠
10-
# 2. 소문자로 다 바꿈
11-
# 3. 뒤집었을 때 같은지 확인
8+
# 알파벳, 숫자임을 판단하고, 소문자로 변환해 준 다음 팰린드롬인지를 확인하는 방식
9+
def mySolution(s: str) -> bool:
10+
temp = ""
1211

13-
temp = ""
14-
# 알파벳이라면
12+
for i in s:
13+
if i.isalnum():
14+
temp += i.lower()
15+
16+
if temp == temp[::-1]:
17+
return True
18+
else:
19+
return False
20+
21+
# 배열을 이용하여서 첫 번째 값과 마지막 값을 비교하여 팰린드롬인지를 확인하는 방식
22+
def listSolution(s: str) -> bool:
23+
list = []
24+
25+
for i in s:
26+
if i.isalnum():
27+
list.append(i.lower())
28+
29+
while len(list) > 1:
30+
if list.pop(0) != list.pop():
31+
return False
32+
33+
return True
34+
35+
# 배열을 이용한 것보다 시간복잡도를 좀 더 개선한 방법 deque 사용
36+
def dequeSolution(s: str) -> bool:
37+
deque = deque()
1538

16-
for i in s:
17-
if i.isalnum():
18-
temp += i.lower()
39+
for i in s:
40+
if i.isalnum():
41+
deque.append(i.lower())
42+
43+
while len(deque) > 1:
44+
if deque.popleft() != deque.pop():
45+
return False
1946

20-
if temp == temp[::-1]:
21-
return True
22-
else:
23-
return False
47+
return True
48+
49+
# 정규식과 문자열 슬라이싱을 이용한 방법
50+
def slicingSolution(s: str) -> bool:
51+
s = s.lower()
52+
s = re.sub('[^a-z0-9]', '', s)
53+
54+
return s == s[::-1]
55+

0 commit comments

Comments
 (0)