<--- 리트코드 125. Valid Palindrome --->

# 팰린드롬 이란

앞뒤가 똑같은 단어나 문장으로 뒤집어도 같은 말이 되는 단어 또는 문장을 말한다.

 

 

# 문제: 주어진 문자열이 팰린드롬인지 확인하라. 대소문자를 구분하지 않으며, 영문자와 숫자만을 대상으로 한다.

 

입력

"A man, a plan, a canal: Panama"

출력

true

 

입력

"race a car"

출력

false



# 풀이

1. 리스트로 변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def palindrome(s):
  strs = []
  for char in s:
    if char.isalnum() == True:
      strs.append(char.lower())
 
  while len(strs) > 1:
    if strs.pop(0!= strs.pop():
      return False
 
  return True
 
= input()
print(palindrome(s))
cs

 

2. 데크 자료형을 이용한 최적화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from collections import deque
 
def palindrome(s):
  strs = deque()
  for char in s:
    if char.isalnum() == True:
      strs.append(char.islower())
 
  while len(strs) > 1:
    if strs.popleft() != strs.pop():
      return False
 
  return True
 
= input()
print(palindrome(s))
cs

 

3. 슬라이싱 사용

1
2
3
4
5
6
7
8
9
import re
 
def palindrome(s):
  s = s.lower()
  s = re.sub('[^a-z0-9]''',s)
  return s == s[::-1]
 
= input()
print(palindrome(s))
cs