개발/Leetcode
Leetcode 125. Valid Palindrome
지산동고라니
2023. 6. 24. 12:09
https://leetcode.com/problems/valid-palindrome/description/
Valid Palindrome - LeetCode
Can you solve this real interview question? 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 cha
leetcode.com
문제
주어진 문자열 s에 대해 대문자는 소문자로 변환하고, 0~9 그리고 알파벳에 속하지않는 문자는 지운 문자열이 palindrome인지 아닌지 판단하라. 만약 palindrome이 맞다면 True 그렇지 않다면 False를 반환
코드
import re
class Solution:
def isPalindrome(self, s: str) -> bool:
new_s = re.sub(r"[^A-Za-z0-9]", "", s).lower()
for i in range(len(new_s) // 2):
if new_s[i] != new_s[-(i+1)]:
# print(new_s[i])
return False
return True
간단한 문제여서 정규식을 이용해보기로 했다. 문제에서 주어진 알파벳 숫자가 아닌 문자에 대해서 발견하면 re.sub 을 이용하여 문자를 치환하여 문제에서 주어진 조건을 달성했고 그 이후에는 for문을 이용해 문자를 순회하면서 palindrome인지 아닌지를 구분하였음.