125. Valid Palindrome
자료구조 & 알고리즘ㅤ/ㅤLeetCode

125. Valid Palindrome

문제

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

 


핵심스킬

  • isalnum()
  • pop()
  • 정규표현식 re
  • 슬라이싱

 

풀이 1

def isPalindrome(s: str)-> bool:
    strs = []
    for char in s:
        if char.isalnum():
            strs.append(char.lower())
    
    while len(strs) > 1:
        if strs.pop(0) != strs.pop():
            return False

    return True

 

풀이 2 -- 슬라이싱

def isPalindrome(s: str)-> bool:
    strs = []
    for char in s:
        if char.isalnum():
            strs.append(char.lower())
    
    s = "".join(strs)
    return s == s[::-1]
  • 매우 빠름

 

풀이 3 -- 정규표현식

import re

def isPalindrome(s: str)-> bool:
    s = s.lower()
    s = re.sub('[^a-z0-9]', '', s) # a~z와 0~9를 

    return s == s[::-1]

 

문제 링크

https://leetcode.com/problems/valid-palindrome/