125. Valid Palindrome Python3

Yelim Kim·2021년 9월 12일
0
post-thumbnail

Problem

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Constraints:

1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.

My code

class Solution:
    def isPalindrome(self, s: str) -> bool:
        new_s = ''.join(filter(str.isalnum, s))
        new_s = new_s.lower()
        if new_s != new_s[::-1]:
            return False
        else :
            return True
    

Review

실행 결과
Runtime(50ms), Memory(14.9MB)

접근 방향:
1. 특수문자 제거하기
2. 출력해놓고 보니 대문자 때문에 안맞더라구요 그래서 전체 다 소문자로 변환해줬습니다.
3. 거꾸로 맞춰봐서 틀리면 바로 False출력 ("다 맞으면 True"보다 빠르지 않을까 생각해봅니다...)

특수문자 제거하기
''.join(filter(str.isalnum, s))
소문자로 변환하기
.lower()
맨 처음 글자부터 맨 끝 글자까지 거꾸로 비교하기
new_s != new_s[::-1]

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글