문제
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:
s2 = ""
# 1. toLower
s = s.lower()
# 2. remove non-alphanumeric characters
for ch in s:
if (ch.isdigit() or
(ord('A') <= ord(ch) <= ord('Z')) or (ord('a') <= ord(ch) <= ord('z'))):
# add to new string
s2 += ch
# 3. judge if it's a palindrome
if s2[::-1] == s2:
return True
return False
해설 풀이
class Solution:
def isPalindrome(self, s: str) -> bool:
l = 0
r = len(s) - 1
while l < r:
while l < r and not self.alphaNum(s[l]):
l += 1
while r < l and not self.alphaNum(s[r]):
r -= 1
if s[l].lower() != s[r].lower():
return False
l, r = l+1, r-1
return True
def alphaNum(self, c):
return (ord('A') <= ord(c) <= ord('Z') or
ord('a') <= ord(c) <= ord('z') or
ord('0') <= ord(c) <= ord('9'))
➤ two pointer 기법 사용
배운 내용
🔑 문제 풀기 전 알아둬야 할 것!
Non-alphanumeric characters refer to those characters that are neither alphabets (a-z) nor numbers(0-9)
🚫 오류 기록
invalid literal for int() with base 10: 'a' Error
➤ ord(ch)가 실패한 이유는 현재 문자 ch가 알파벳이나 숫자가 아닌 경우에는 해당 문자를 정수로 변환할 수 없기 때문
✏️ 배움 기록
문자열인지 숫자인지 판단
- 숫자판별 - isdigit()
s = "28212"
print(s.isdigit()) # True
# contains alphabets and spaces
s = "Mo3 nicaG el l22er"
print(s.isdigit()) # False
2. 문자열 판별 - isalpha()
name = "Monica"
print(name.isalpha()) # True
3. 숫자 + 문자열 판별 isalnum( )
name = "M234onica"
print(name.isalnum()) # True
'Coding Test' 카테고리의 다른 글
[TIL/05.08] Leetcode: Best Time to Buy and Sell Stock (Python) (0) | 2024.05.10 |
---|---|
[TIL/05.07] Leetcode: 3Sum (Python) (0) | 2024.05.07 |
[TIL/05.06] Leetcode: Group Anagrams (Python) (0) | 2024.05.06 |
[TIL/04.12] Algorithm: Greedy (Java) (0) | 2024.04.13 |
[TIL/04.11] Algorithm: 정렬 (Java) (0) | 2024.04.12 |