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
풀이 과정
문자열 s가 팰린드롬인지 확인해주는 기능을 구현하면 된다.
팰린드롬이란 문자열을 뒤집어도 똑같은 문자열을 말한다. 예를 들면 기러기, 토마토, 스위스, 인도인, 별똥별, 우영우, 역삼역 등의 단어는 모두 팰린드롬을 만족하는 단어이다.
문제의 조건에 맞게 대문자는 소문자로 바꿔주고, 알파벳이 아닌 문자는 문자열에서 전부 무시해준 다음, 문자열 s와 s[::-1]을 비교해 같으면 팰린드롬 문자열이라고 판단하였다.
굳이 s와 동일한 원소를 가진 s'를 선언해서 s'.reverse()로 뒤집은 다음 s == s'인지 비교할 필요 없이 문자열 슬라이싱으로 더 빠르게 해결할 수 있다.
소스 코드
class Solution:
def isPalindrome(self, s: str) -> bool:
chars = []
for char in s:
if char.isalnum():
char = char.lower()
chars.append(char)
if chars == chars[::-1]:
return True
else:
return False
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 937. Reorder Data in Log Files [Python] (0) | 2022.07.21 |
---|---|
LeetCode - 344. Reverse String [Python] (0) | 2022.07.19 |
LeetCode - Trapping Rain Water [Python] (0) | 2022.07.07 |
LeetCode - Two Sum [Python] (0) | 2022.07.07 |
leetcode - Group Anagrams [Python] (0) | 2022.07.07 |