Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
[Example 1]
Input: "A man, a plan, a canal: Panama"
Output: true
[Example 2]
Input: "race a car"
Output: false
class Solution:
def isPalindrome(self, s: str) -> bool:
res = ''.join(filter(lambda x : x.isalnum(), s)).lower()
return res == res[::-1]
Palindrome는 앞으로 읽어도, 뒤로 읽어도 똑같은 단어나 구를 의미하며, '내 이름은 이효리, 거꾸로 해도 이효리'에서 '이효리'와 똑같은 개념이라고 할 수 있다.
먼저, 특수문자를 제거해줘야 하기 때문에 문자(영어&한글 모두 가능)와 숫자를 리턴해주는 isalnum()을 사용해서 filter 처리를 해주었고, 모두 소문자로 만들어 주었다.
그리고 역순으로 했을 때와 비교를 통해 결과를 반환하였다.
481 / 481 test cases passed.
Status: Accepted
Runtime: 40 ms
Memory Usage: 14.8 MB
isalnum()과 같은 메소드를 알고리즘에서 자주 사용하는 것으로 알고 있는데, 몇가지 더 알아보게 되었다.
이 외에도 isnumeric(), isdecimal(), isspace() 와 같은 메소드가 있지만 다음에 더 자세히 알아볼 예정이다.