
문자열 s가 주어졌을때, 이 문자열이 palindrome인지 판별하시요. alphanumeric character에 대해서만 고려한다.
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.
문제 풀이의 공통된 방법으로는 'alphanumeric 문자들을 따로 모아야 한다는 것.'이다.
이 풀이에서는 deque를 이용하여 deque의 맨 앞의 문자와, 맨 뒤의 문자를 길이가 2 이상인 동안에 계속 비교하면서 풀이한다.
from collections import deque
class Solution:
def isPalindrome(self, s: str) -> bool:
deque = deque()
# Alphanumeric을 lowercase로 변환하여 deque에 삽입한다.
for char in s:
if char.isalnum():
deque.append(char.lower())
# deque의 길이가 2 이상일 때, pop()과 popleft()의 크기를 비교한다.
while len(deque) > 1:
if deque.pop() != deque.popleft()
return False # palindrome이 아니므로 False를 반환하며 종료한다.
return True #palindrome이므로 True를 반환하며 종료한다.
class Solution:
def isPalindrome(self, s: str) -> bool:
p_str: str = ''
# Alphanumeric을 lowercase로 변환하여 deque에 삽입한다.
for char in s:
if char.isalnum():
p_str += char.lower()
# 문자열과 뒤집은 문자열이 같은지 비교한 결과를 반환한다.
return p_str == p_str[::-1]