문자열 조작? 문자열을 변경하거나 분리하는 등의 여러 과정
문제 1. 유효한 팰린드롬
# 리스트로 변환
strs =[]
for char in s:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.pop(0) != strs.pop(): #첫번째 원소 마지막 원소 비교
return False
isalnum() ⇒ 영문자,숫자 여부 판별
#deque(데크) 자료형을 이용한 최적화
def isPalindrome(self,s:str) -> bool:
strs: Deque = collections.deque()
for char in s:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.popleft() != strs.pop():
return False
return True
deque의 popleft()는 O(1)이기 때문에 1번 풀이보다 성능이 훨씬 좋다
import re
def isPalindrome(self,s:str) -> bool:
s = s.lower()
#정규식으로 불필요한 문자 필터링
s = re.sub('[^a-z0-9]','',s)
return s == s[::-1] #슬라이싱을 통해 문자열을 뒤집어줌