문제 링크 : leetcode.com/problems/valid-palindrome/

 

Valid Palindrome - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이 문제는 문자열의 알파벳과 숫자의 배열이 Palindrome(문자열을 역순으로 해도 같은 문자열)인지 확인하면 되는 문제이다.

 

풀이방법

1. isalnum() 함수를 이용하여 특수문자를 제외해주고

2. 대소문자를 구문하지 않으므로 lower() 함수를 이용하여 소문자로 만들어서

3. Palindrome인지 확인한다.

 

Palindrome인지 확인하는 방법에는 여러가지가 있는데

1. start와 end를 이동하며 비교하기

2. pop(0) == pop()으로 비교하기

3. 중간부터 왼쪽과 오른쪽으로 가면서 비교하기

등이 있으나 파이썬에서는 list slicing을 이용해서 아주 쉽게 Palindrome을 확인할 수 있다.

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

아직 파이썬을 파이썬 답게 쓰지 못해서 s == s[::=1]같은게 되는 줄 몰랐다.

맨날 앞뒤 인덱스 비교해가면서 풀었는데 알아두면 참 좋은 테크닉인 것 같다.

+ Recent posts