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.
주어진 문장에 대문자가 있다면 모두 소문자로 변경하고,
알파벳과 숫자가 아닌 모든 것은 제거한다 (띄어쓰기, 따옴표 등 모두 제거)
앞에서 읽었을 때와 거꾸로 읽었을 때 똑같이 읽혀야한다.
이 문장은 영문자와 숫자만을 포함한다.
이 문자가 회문이면 true를 반환하고, 회문이 아니라면 false를 반환한다.
1. 주어진 문장 s를 lower를 사용하여 모두 소문자로 변경한다.
2. 알파벳과 숫자가 아닌 모든 항목은 제거한다. -> ** alnum 사용 **
3. 제대로 읽었을 경우, 거꾸로 읽었을 경우를 비교해서 "true" or "false"를 출력한다. -> [::-1] 사용
# 빈 저장소 생성
temp = ""
# 소문자로 변경한 문자 저장
lower_text = s.lower()
# 소문자로 변경 후에 isalnum으로 문자/숫자가 아닌 모든 항목 제거 후, temp로 저장
for s_text in lower_text:
if s_text.isalnum():
temp += s_text
# print(temp)
# -> amanaplanacanalpanama
# temp와 temp[::-1] 를 비교
if temp == temp[::-1]:
print(f"true")
else:
print(f"false")
class Solution:
def isPalindrome(self, s: str) -> bool:
temp = ""
s_text = s.lower()
for s in s_text:
if s.isalnum():
temp += s
print(temp)
if temp == temp[::-1]:
print(f"true")
else:
print(f"false")
문자열에서 특정 타입만 뽑아내는 방법
1. 숫자만 뽑아내기
isdigit()
문자만 뽑아내기
isalpha()문자 & 숫자만 뽑아내기
isalnum()
leetcode
아니 대체 왜지?
print 로는 제대로 찍히는데 leetcode에서는 이번에도 output으로 다르게 찍힌다..
모두 false가 뜨는데... 음...
def isPalindrome(self, s: str) -> bool:
이 부분 때문에 안되는 것 같긴 한데...
이 글 에서 참고한 것 처럼 리스트컴프리헨션을 사용함
class Solution:
def isPalindrome(self, s: str) -> bool:
strs = [char.lower() for char in s if char.isalnum()]
return strs == strs[::-1]
...?
위에서 언급한 대로
def isPalindrome(self, s: str) -> bool:
이 부분을 생각 못한건 맞다...
리스트 컴프리헨션에 대해서 더 자세히 공부해야겠다..
그리고 주어진 함수를 제대로 읽는 능력을 더 길러야겠다...
시간도 이리 적게 걸리다니?