반응형
125. Valid Palindrome
Easy
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.
Constraints:
1 <= s.length <= 2 * 105
s
consists only of printable ASCII characters.
나의 코드
class Solution:
def isPalindrome(self, s: str) -> bool:
word = ""
for i in s:
if i.isalpha() or i.isdigit():
word += i
word = word.lower()
if len(word) == 0: return True
if len(word) % 2 != 0:
A = word[:len(word) // 2]
B = word[(len(word)//2)+1:][::-1]
if A == B: return True
else: return False
if len(word) % 2 == 0:
A = word[:len(word) // 2]
B = word[(len(word)//2):][::-1]
if A == B: return True
else: return False
728x90
반응형
'알고리즘 > LeetCode_Grind75' 카테고리의 다른 글
Grind75 - 121. Best Time to Buy and Sell Stock 파이썬 (0) | 2024.11.19 |
---|---|
Grind75 - 704. Binary Search 파이썬 (0) | 2024.11.18 |
Grind75 - 242. Valid Anagram 파이썬 (0) | 2024.11.13 |
Grind75 - 20. Valid Parentheses 파이썬 (0) | 2024.10.27 |
Grind75 - 1. Two Sum 파이썬 (0) | 2024.10.21 |