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.
풀이
문자열이 앞뒤로 동일하면 회문이라한다. 이 문제는 숫자와 영어소문자로만 구분해서 앞뒤가 같은 회문인지 확인하는 문제이다.
문자열을 구분하기 위해서 ord함수를 사용하여 아스키코드로 변환하여 소문자 대문자 숫자를 구분해줬다.
이후에 left ,right 두 개의 포인터를 둔 후 양끝에서 하나씩 확인하는 방법으로 구현했다.
class Solution(object):
def isPalindrome(self, s):
word =[]
for i in s:
ii = ord(i)
if 96<ii<123:
word.append(i)
elif 47<ii<58:
word.append(i)
elif 64<ii<91:
word.append(i.lower())
right=len(word)-1
left = 0
result= True
while left<right:
if word[left] !=word[right]:
result = False
right-=1
left+=1
return result
다른 사람의 코드
def isPalindrome(self, s):
l, r = 0, len(s)-1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l <r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l +=1; r -= 1
return True
단순하게 투포인터를 사용한 후 isalnum 함수를 통해 문자와 숫자를 구분한 후 투포인터를 사용했다.
아..아스키코드말고 issalnum()을 통해서 숫자와 문자를 구분하는 방법도 있구나
다음에 사용해봐야겠다.
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 3. Longest Substring Without Repeating Characters (0) | 2023.08.29 |
---|---|
LeetCode 167. Two Sum II - Input Array Is Sorted (0) | 2023.08.28 |
LeetCode 55. Jump Game (0) | 2023.08.25 |
LeetCode 121. Best Time to Buy and Sell Stock II (0) | 2023.08.25 |
LeetCode 121. Best Time to Buy and Sell Stock (0) | 2023.08.25 |