펠린드롬이란?
https://ko.wikipedia.org/wiki/%ED%9A%8C%EB%AC%B8
거꾸로 읽어도 똑같은 말을 말합니다.
요즘 분들을 잘 모르시겠지만 슈퍼주니어 노래중에 로꾸꺼라는 노래가 있는데
이게 펠린드롬입니다.
=> 거꾸로해도 수박이박수이지요
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
- 모든 uppercase letters를 lower letters로,
- 모든 알파벳과 숫자가 아닌 문자를 제거,
- 거꾸로해도 똑같으면 True 아니면 False를 반환하는 과정을 진행해야 합니다.
코드를 입력하세요
import re
class Solution:
def isPalindrome(self, s: str) -> bool:
s = s.lower()
s = re.sub('[^a-z|^0-9]','',s)
if s[::-1] == s:
return True
else:
return False
비교적으로 많이 쉬운 문제인 것 같아요.
해설: re.sub는 정규식 관련 라이브러리로, 영문자 아니면 전부 삭제하는 코드이며,
문자열에 [::-1]의 의미는 처음부터 끝까지 역순으로 나타냅니다
s = 'abc'
s[::-1] 의 값은 'cba'가 됩니다.
참고로 isalnum() 메서드를 사용해서 풀 수 있습니다.(이 경우에는 문자열을 하나씩 인덱싱 하여서 풀어야 합니다😊
https://wikidocs.net/4308
를 참고하면 정규식에 대해 더 자세하게 알 수 있습니다.😍