본문 바로가기
성장중/알고리즘 인터뷰

파이썬 알고리즘 인터뷰 p.138 유효한 팰린드

반응형

알고리즘 인터뷰 p.138 유효한 팰린드롬

leetcode: 125번

leetcode.com/problems/valid-palindrome/

 

Valid Palindrome - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제:

Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

 

저는 팰린드롬이 뭔지를 몰라서 팰린드롬부터 찾아봤습니다.

팰린드롬 = 회문. 토마토, 기러기 같이 앞으로 읽으나 뒤로 읽으나 똑같은 단어나 문장. 

Example:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
class Solution:
    def isPalindrome(self, s: str) -> bool:
        strs = []
        for c in s:
            if c.isalnum(): # isalnum는 영문자, 숫자 여부를 판별하는 함수
                strs.append(c.lower()) # strs에 lower을 사용해 모두 소문자로 만든 다음 추가
            
        
        while len(strs) > 1:
            if strs.pop(0) != strs.pop(): # pop는 인덱스 지정이 가능하다.
                return False              # 그냥 pop를 진행하면 마지막 값이 나오지만 
                                          # pop(0) 이렇게 지정하면 맨 앞의 값이 나온다.
        return True
# Pythonic
class Solution:
    def isPalindrome(self, s: str) -> bool:
        s_filter = ''.join(filter(str.isalnum, s)).lower()
        return s_filter[::-1] == s_filter

 

분명 전에 똑같은 책으로 똑같이 공부했는데, 저란 멍청이는 다 너무 새로운 거 같습니다.

list 방식은 책 p.139에 있는 방식의 코드이고 두 번째는 다른 분들은 뚝딱뚝딱 만드실 텐데.. 전 두 시간 정도 걸린 거 같습니다.

블로그 이름처럼 성장하는 모습 꼭 보여드리고 싶네요!

반응형