CS/Algorithm

[1] 문자열 조작(1) leetcode 125. Valid Palindrome

juyeong 2023. 10. 9. 19:50
반응형

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

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

- 문자열 조작은 코테의 빈출 문제, 실무에서도 자주 사용된다.

- 대부분 언어별 내장 기능이 잘 되어있으므로 활용하는 방법에 익숙해지자. (나는 파이썬)

 

이 문제를 풀이하는 방법은 크게 3가지

 

1) 데이터 전처리를 통해 리스트로 변환

2) deque 자료형 활용

3) 슬라이싱 활용

-> 모두 파이썬 내장 기능을 알아야 풀 수 있는 방법이다. 

 

1) 데이터 전처리를 통해 리스트로 변환

class Solution1:
    def isPalindrome(self, s: str) -> bool:
        
        #1. 데이터 전처리 -> ['a','m', .. '[a]']
        s = [] 
        for char in s:
            if char.isalnum():
                strs.append(char.lower())
                
        #2. 팰린드롬 여부 판별
        while len(strs) > 1: # 예외처리
            if strs.pop(0) != strs.pop():
                return False
            # 모두 통과했다면 True 리턴

 

2) deque 자료형 활용

class Solution2:
    def isPalindrome(self, s: str) -> bool:
        
        # 자료형 데크로 선언
        strs:Deque = collections.deque()
            
        for char in s: 
            if char.isalnum():
                strs.append(char.lower())
                
        while len(strs) > 1: 
            if strs.popleft() != strs.pop():
                return False
            
        return True

 

 

 

pop() vs popleft

gpt야 고마워 ..ㅎ

 

 

3) 슬라이싱 활용

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()
        # 정규식 활용
        s = re.sub ('[^a-z0-9]','',s)
        
        # 뒤집고 true, false 판별 
        return s == s[::-1]

성능 2번보다 2배 빠름 

어지간하면 문자열을 리스트로 변환했을 때는 슬라이싱 방법쓰자

반응형