Python
[Python] 예제 : 회문(Palindrom)
SangRok Jung
2022. 8. 29. 21:43
반응형
문제
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.
해석
- 문자열을 소문자로 변환. -> lower()
- 공백 제거. -> replace(" ", "")
- 영문자만 추출 -> list(filter(str.isalpha, String)
- 리스트를 스트링으로 변환 "".join(list)
- 문자열 뒤집기 -> Strig[::-1]
s1 = "".join(list(filter(str.isalpha, input("Enter the sentence").lower().replace(" ", ""))))
s2 = s1[::-1]
if s1 == s2 :
print(" ""%s"" is a palindrome. " % s2)
elif s1 != s2 :
print(" ""%s"" is not a palindrome. " % s2)
반응형