Diary, Data, IT

[LeetCode] 125. Valid Palindrome - Python 본문

Coding Test/LeetCode

[LeetCode] 125. Valid Palindrome - Python

라딘 2023. 4. 10. 22:46

 

[LeetCode] 125. Valid Palindrome - Python

 

 

Valid Palindrome - LeetCode

Can you solve this real interview question? Valid Palindrome - 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 cha

leetcode.com

 

문제

주어진 문자열이 팰린드롬인지 확인하라. 대소문자를 구분하지 않으며, 영문자와 숫자만을 대상으로 한다.

팰린드롬이란, 앞뒤가 똑같은 단어나 문장으로, 뒤집어도 같은 말이 되는 단어 또는 문장을 뜻한다.

 

아이디어

입력에서 특수문자나 공백을 포함한 문자열들이 주어지는데, 팰린드롬인지 확인하기 위해서는 이들을 제거하는 과정이 필요합니다. 또한, 대소문자를 구분하지 않으므로, 모두 대문자나 소문자로 통일해주어야 합니다.

이렇게 전처리를 마친 문자열을 리스트로 변환한 뒤, 리스트의 순서를 거꾸로 정렬하여 동일한지 확인하면 됩니다.

 

 

코드

class Solution:
    def isPalindrome(self, s: str) -> bool:

        #대소문자를 구분하지 않으며, 영문자와 숫자만 포함해야 함 -> isalnum, lower

        list_s = [s1.lower() for s1 in s if s1.isalnum()]

        if list_s[::-1] == list_s:
            return True
        else:
            return False

 

코드 2

class Solution:
    def isPalindrome(self, s: str) -> bool:

        #대소문자를 구분하지 않으며, 영문자와 숫자만 포함해야 함 -> isalnum, lower

        list_s = [s1.lower() for s1 in s if s1.isalnum()]

        while len(list_s) > 1:  #첫 글자와 마지막 글자를 하나씩 추출해가며 같은지 확인
            if list_s.pop(0) != list_s.pop():
                return False
    
        return True