알고리즘/리트코드
문자열 조작 : 유효한 팰린드롬(리트코드 125번)
bewisesh91
2021. 12. 14. 21:19
728x90
▶ 문제 : https://leetcode.com/problems/valid-palindrome/
Valid Palindrome - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
##### 문제 #####
주어진 문자열이 팰린드롬인지 확인하라. 대소문자를 구분하지 않으며, 영문자와 숫자만을 대상으로 한다.
##### 입력 #####
"A man, a plan, a canal, : Panama"
##### 출력 #####
True
▶ 접근 방법
팰린드롬은 앞뒤가 똑같은 단어나 문장을 의미한다.
리스트로 변환하여 맨앞과 맨뒤를 하나 씩 비교하는 방법, 슬라이싱을 방법 등 다양한 풀이가 가능했다.
▶ 풀이 코드
ex_string = "A man, a plan, a canal, : Panama"
########################################################
def is_palindrome_using_list(string: str) -> bool:
strs = []
for char in string:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.pop(0) != strs.pop():
return False
return True
print(is_palindrome_using_list(ex_string))
########################################################
from collections import deque
def is_palindrome_using_deque(string: str) -> bool:
strs = deque([])
for char in string:
if char.isalnum():
strs.append(char.lower())
while len(strs) > 1:
if strs.popleft() != strs.pop():
return False
return True
print(is_palindrome_using_deque(ex_string))
########################################################
import re
def is_palindrome_using_slicing(string: str) -> bool:
string = string.lower()
string = re.sub('[^a-z0-9]', '', string)
return string == string[::-1]
print(is_palindrome_using_slicing(ex_string))
▶ 관련 링크