less than 1 minute read

125. Valid Palindrome

문제 링크

https://leetcode.com/problems/valid-palindrome/description/?source=submission-ac

문제 설명

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.

제한사항

  1. 1 <= s.length <= 2 * 105
  2. s consists only of printable ASCII characters.

입출력 예 #1

  1. 1Input: s = “A man, a plan, a canal: Panama
  2. Output: tru
  3. Explanation: “amanaplanacanalpanama” is a palindrome..

입출력 예 #2

  1. Input: s = “race a car
  2. Output: fals
  3. Explanation: “raceacar” is not a palindrom

입출력 예 #3

  1. Input: s = “
  2. Output: tru
  3. Explanation:s is an empty string “” after removing non-alphanumeric characters. Since an empty string reads the same forward and backward, it is a palindrome

문제 풀이

문자열 조작 함수를 사용하여 쉽게 해결할 수 있다.

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

Comments