Study/problem solving

[LeetCode] 125. Valid Palindrome

minzihun 2022. 9. 10. 06:27

 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.

 

* palindrome: 역순으로 읽어도 같은 말이나 구절, 숫자 등을 의미한다.

 

Example:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

 

 문자열은 모두 소문자로 변경한 뒤, 특수문자와 스페이스를 제거하려했다. 특수문자와 스페이스를 제거하는 과정에서 이를 리스트에 넣고 반복문을 통해 하나씩 공백으로 제거하려했지만, 특수문자 수만큼 반복문을 돌아야하기에 비효율적이라는 생각이 들어 정규식을 이용하기로 했다. 정규식을 사용하려면 re를 import해야한다. re는 regular expression의 약자로 정규식 관련 연사자들이 들어있는 라이브러리다. 정규식만 따로 한번 공부해야 확실히 써먹을 수 있을 것 같다는 생각이 들었다. sub함수를 이용해 숫자와 알파벳이 아닌 것을 모두 공백으로 대체하고 소문자로 바꿨다.

 

 처음에는 리스트에 넣어 reverse함수를 이용해 뒤집은 다음 다시 문자열로 만들어 비교하려 했지만, 계속 다시 문자열로 만드는 과정에  typeerror can only join an iterable가 발생하였다. 그래서 리스트에 넣지 않고 문자열을 뒤에서부터 추출하는 형태로 반전시켰다.

import re

class Solution:
    def isPalindrome(self, s: str) -> bool:
        
        # remove asterisk and blank using regular expression
        filtered_str = re.sub(r"[^a-zA-Z0-9]", '', s)
        
        # change lower case to upper case
        result = filtered_str.lower()

        # reverse a result str
        result_reversed = result[::-1]
        
        return result == result_reversed

 

 리스트 함수를 사용하면 적용되고 원래 리스트에 그 값이 저장되는데 이 과정에서 그 저장된 값을 새로운 변수에 할당하면 None으로 할당돼서 typeerror can only join an iterable를 일으킨다. 그래서 이 때는 새로운 변수에 할당하는 과정을 없애고 함수만 적용시키면 해결이 된다. 그렇지만 문자열을 반대로 추출하는 방법이 훨씬 간단한 것 같다. 하지만 결과적으로 후자의 방법이 45ms로 기존 문자열 추출을 이용한 78m보다 빠르다.

import re

class Solution:
    def isPalindrome(self, s: str) -> bool:
        
        # remove asterisk and blank using regular expression
        filtered_str = re.sub(r"[^a-zA-Z0-9]", '', s)
        
        # change lower case to upper case
        result = filtered_str.lower()

        # reverse a result with list method
        result_list = list(result)
        result_list.reverse()
        result_reversed = ''.join(result_list)
        
        return result == result_reversed