반응형
Valid Palindrome
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
펠린드롬은 문자열 데칼코마니라고 생각하면 될 듯 하다. 가운데를 기준으로 서로 마주보듯 이루어져 있는 문자열이다. 처음엔 문제의 조건대로 하나씩 비교하면서 넘어갔었는데, 다른 분들의 풀이를 보다가 문자열을 뒤집어서 비교했을 때도 역시 같아야 한다는 것을 생각할 수 있었다. 이런 방식으로 생각할 수 있구나.
반응형
'알고리즘 스터디' 카테고리의 다른 글
[Leetcode/파이썬] 57. Insert Interval (0) | 2025.09.22 |
---|---|
[Leetcode/파이썬] 242. Valid Anagram (0) | 2025.09.22 |
[Leetcode/파이썬] 1. Two Sum (1) | 2025.09.14 |
[Leetcode/파이썬] 64. Minimum Path Sum (0) | 2025.09.14 |
[Leetcode/파이썬] Insert Delete GetRandom O(1) (0) | 2025.09.14 |