00_valid_palindrome

Numeric_combo·2024년 6월 20일

알고리즘-공부

목록 보기
1/6

125 valid palindrome

내가 쓴 것:

import re

def check_palindrome(string):
    cleaned_string = re.sub(r'[^A-Za-z0-9]', '', string).lower() # get rid of special characters and lower alphabets
    
    read_from_left = []
    for i in cleaned_string:
        read_from_left.append(i)
    
    read_from_right = []
    for i in reversed(cleaned_string): # read string backwards
        read_from_right.append(i)
    
    if read_from_left == read_from_right:
        print('true')
        #return 'true'
    else:
        print('false')
        #return 'false'

솔루션 중 하나

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

        return s == s[::-1] 
  • 문자열 슬라이싱에서 s[::-1]은 s에 담긴 문자열을 뒤집어 입력하는 것을 의미한다 (예: s = "하이루"가 있다면, s[::-1] == 루이하)
profile
덕질기록용

0개의 댓글