Programming/leetcode
125. Valid Palindrome
홍열
2021. 1. 21. 09:06
728x90
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
- 난이도 Easy
- 일명 '회문'으로 문제
ex) abba -> true
abbc -> false - 다만, 문제에서는 알파벳과 숫자만 취급하므로 그에 따른 처리가 필요하다.
- 풀이
def isPalindrome(s:str)->bool:
#전통적인 for문 이용
i, j = 0, len(s)-1
while i<j:
if not s[i].isalnum():
i+=1
continue
if not s[j].isalnum():
j-=1
continue
if s[i].lower() != s[j].lower():
return False
i+=1
j-=1
return True
#lower 이용, list join
#coverter_s = [item.lower() for item in s if item.isalnum()]
#return ''.join(coverter_s) == ''.join(coverter_s[::-1])
#정규식 풀이
#coverter_re = re.sub('[^a-z0-9]', '', s.lower())
#return s == coverter_re[::-1]
print(isPalindrome("A man, a plan, a canal: Panama"))
print(isPalindrome("race a car"))