알고리즘 스터디

[Leetcode/파이썬] 125. Valid Palindrome

난쟁이 개발자 2025. 9. 22. 17:17
반응형

 

Valid Palindrome

Difficulty: Easy


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.

 

class Solution:
    def isPalindrome(self, s: str) -> bool:
        res = ''
        for char in s :
            if char.isalnum() :
                res += char.lower()

        return res == res[::-1]
class Solution:
    def isPalindrome(self, s: str) -> bool:
        res = ''
        for char in s :
            if char.isalnum() :
                res += char.lower()
        
        n = len(res)

        left, right = 0, n - 1

        while left <= right :
            if res[left] == res[right] :
                left += 1
                right -= 1
            else :
                return False
        
        return True

펠린드롬은 문자열 데칼코마니라고 생각하면 될 듯 하다. 가운데를 기준으로 서로 마주보듯 이루어져 있는 문자열이다. 처음엔 문제의 조건대로 하나씩 비교하면서 넘어갔었는데, 다른 분들의 풀이를 보다가 문자열을 뒤집어서 비교했을 때도 역시 같아야 한다는 것을 생각할 수 있었다. 이런 방식으로 생각할 수 있구나.

반응형