Algorithm/Leet code

[leetcode] Valid Palindrome (python)

juyeong 2023. 2. 21. 16:51
반응형

Q. 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 characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

 

1. 리턴타입 boolean

2. 회문을 돌면서 모두 체크할 것인지, 정규 표현식을 쓸 것인지 고민할 필요가 있습니다. 만약 회문을 돈다면 .isalnum()(영문자, 숫자 체크 함수)로 체크한 뒤 pop() 함수를 사용하는 방법과 collections 의 데크(deque)를 사용하는 방법이 있습니다.

3. 제가 사용한 방법은 re 를 import 하여 정규표현식을 사용한 것입니다

 

A. 

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()
        s = re.sub ('[^a-z0-9]','',s)
        
        return s == s[::-1]

 

반응형