유효한 팰린드롬
https://leetcode.com/problems/valid-palindrome/
주어진 문자열이 팰린드롬인지 확인하라. 대소문자를 구분하지 않으며, 영문자와 숫자만을 대상으로 한다.
Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
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.
Constraints:
- 1 <= s.length <= 2 * 105
- s consists only of printable ASCII characters.
-----------------------------------------------------------------------------------------------------------------------------------
풀이 1. 리스트로 변환
def isPalindrome(self, s: str) -> bool:
strs = []
for char in s:
if char.isalnum():
strs.append(char.lower())
# 팰린드롬 여부 판별
while len(strs) > 1:
if strs.pop(0) != strs.pop():
return False
return True
풀이 2. 데크 자료형을 이용한 최적화
def isPalindrome(self, s:str) -> bool:
#자료형 데크로 선언
strs: Deque = collections.deque()
for char in s:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.popleft() != strs.pop():
return False
return True
풀이 3. 슬라이싱 사용
def isPalindrome(self, s:str) -> bool:
s = s.lower()
#정규식으로 불필요한 문자 필터링
s = re.sub('[^a-z0-9]', '', s)
return s == s[::-1] #슬라이싱
728x90
'Python > 코딩테스트' 카테고리의 다른 글
[Leetcode] 344.Reverse String (0) | 2021.06.24 |
---|---|
[Leetcode] 238. Product of Array Except Self (0) | 2021.06.23 |
[Leetcode] 121.Best tiem to Buy and Sell Stock (0) | 2021.06.21 |
[Leetcode] 42.Trappling Rainbow Water (0) | 2021.06.17 |
[Leetcode] 1. Tow Sum (0) | 2021.06.16 |