Skip to content

Latest commit

 

History

History
34 lines (25 loc) · 1.31 KB

File metadata and controls

34 lines (25 loc) · 1.31 KB

🧡 125. Valid Palindrome

  • Date : 2021.07.04(일)
  • Time : 10분

Problem

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

Constraints

  • 1 <= s.length <= 2 * 10^5
  • s consists only of printable ASCII characters.

Example

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

풀이

    def isPalindrome(self, s: str) -> bool:
        new_string = re.sub(r"[^a-zA-Z0-9]","",s)
        new_string = new_string.lower()
        if new_string == new_string[::-1] :
            return True
        else :
            return False

: 먼저 문자열에서 숫자와 영어를 제외하고는 회문을 평가하는데 사용하지 않는다. 그렇기 때문에 정규표현식을 사용할 수 있는 re 라이브러리를 import해서 사용한다. ^ 는 제외하고를 뜻한다. 먼저, 영어와 숫자를 제외하고는 모두 제거해주었다. 그리고는 대소문자를 신경쓰지 않기위해 모두 소문자로 변경해주었다. 이때 대문자로 변경해도 상관은 없다. 이제 회문인지 아닌지 판단해주면 된다. [::-1]를 하면 문자열이 반대로 뒤집힌다. 이를 이용해 같다면 true를 반환해주었다.