팰린드롬 검사기
Source: Dev.to
palindrome이란?
palindrome은 단어, 구절, 숫자 또는 기타 문자 시퀀스로, 앞에서 읽으나 뒤에서 읽으나 같은 의미를 갖는(공백, 구두점, 대소문자를 무시) 문자열을 말합니다.
예시
| Input | Result |
|---|---|
racecar | True |
A man a plan a canal Panama | True |
hello | False |
Python 솔루션
def is_palindrome(s):
"""
Checks if a string is a palindrome.
Ignores case and spaces.
"""
s = s.lower()
s = s.replace(" ", "")
return s == s[::-1]
# Test cases
print(is_palindrome("wilabaliw")) # True
print(is_palindrome("A man a plan a canal Panama")) # True
작동 원리
-
소문자로 변환
s = s.lower()이를 통해
"Racecar"와"racecar"가 동일한 문자열로 취급됩니다. -
공백 제거
s = s.replace(" ", "")"A man a plan..."과 같은 구절에서 공백은 palindrome 판별에 영향을 주지 않으므로 제거합니다. -
역순 문자열과 비교
return s == s[::-1]s[::-1]은 문자열의 역순 복사본을 생성합니다. 정제된 원본 문자열이 역순과 같다면 함수는True를 반환하고, 그렇지 않으면False를 반환합니다.
행복한 코딩 되세요!