[LeetCode] Valid Palindrome

뚜니어리·2023년 8월 28일
0

알고리즘

목록 보기
5/5
post-thumbnail

📚 문제

Valid Palindrome

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.

조건

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

✏️ 문제 해석

  • palindrome : 회문 == 앞으로 읽어도 거꾸로 읽어도 똑같은 문장
    ex) level, 토마토

주어진 문장에 대문자가 있다면 모두 소문자로 변경하고,

알파벳과 숫자가 아닌 모든 것은 제거한다 (띄어쓰기, 따옴표 등 모두 제거)

앞에서 읽었을 때와 거꾸로 읽었을 때 똑같이 읽혀야한다.

이 문장은 영문자와 숫자만을 포함한다.

이 문자가 회문이면 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")

💡 leetcode 에 작성한 코드

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")

🪄 새로 알게 된 - isalnum

문자열에서 특정 타입만 뽑아내는 방법
1. 숫자만 뽑아내기
isdigit()

  1. 문자만 뽑아내기
    isalpha()

  2. 문자 & 숫자만 뽑아내기
    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:

이 부분을 생각 못한건 맞다...

리스트 컴프리헨션에 대해서 더 자세히 공부해야겠다..
그리고 주어진 함수를 제대로 읽는 능력을 더 길러야겠다...

시간도 이리 적게 걸리다니?

profile
삽질과 저장소의 그 중간

0개의 댓글