💡코딩테스트/Leetcode

유효한 팰린드롬 | Valid Palindrome

두_두 2023. 6. 6. 13:13

 

팰린드롬

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

 

 

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

 

정규식을 이용한 풀이

정규식 re를 이용해서 문자와 숫자를 제외한 글자를 제거하고 앞뒤를 비교해준다 

re.sub('바꾸고 싶은 표현', '바꿀 표현', 바꾸고 싶은 문장)
class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()
        s = re.sub('[^a-z0-9]', '', s)

        return s == s[::-1]

 

리스르를 이용한 풀이

글자 하나씩 돌아가면서 문자인지 숫자인지 판별해서 arr에 넣어주고 앞뒤를 비교한다 

class Solution:
    def isPalindrome(self, s: str) -> bool:
        arr = []
        for i in s:
            if i.isalnum():
               arr.append(i.lower())

        return arr == arr[::-1]

 

 

 

728x90