파이썬

[리트코드] 125 _ 유효한 팰린드롬

김고찰 2022. 1. 12. 12:44
for char in s:
            if char.isalnum():
                strs.append(char.lower())

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

(팰린드롬(Palindrome) ? 앞뒤가 똑같은 단어나 문장을 말함)


예시 : 

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.

해결 : 

class Solution:
    def isPalindrome(self,s:str)-> bool:
        strs=[]
        for char in s: # 특수문자를 거르기 위한 전처리 과정 
            if char.isalnum(): #isalnum() : 숫자와 문자 -> True, 특수문자 -> False
                strs.append(char.lower()) # .lower() 모두 소문자로 통일

        while len(strs)>1:
            if strs.pop(0)!=strs.pop():
                return False
        return True