[Leetcode/Python] Valid Palindrome

지구인 ㅣ 2022. 8. 21. 00:19

728x90
Top Interview Questions 의 Easy Collection에 있는 문제입니다.  
문제는 여기서 볼 수 있습니다.

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.

 

Example 1:

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

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
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.

 

Constraints:

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

풀이방법

- s.lower() : 입력인 s를 소문자로 바꾸고

- [^0-9a-z] : 소문자와 숫자를 제외한 것은 모두

- "" : 제거한다.

- 정제된 문자열을 맨 앞뒤부터 시작해 중간 지점까지 서로 같은 문자인지 비교한다.

 

Code:

import re

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = re.sub(r"[^0-9a-z]", "", s.lower())
        for i in range(len(s)//2):
            if s[i] != s[-i-1]:
                return False
        return True

 

728x90