LeetCode - 125.Valid Palindrome

Jade J·2021년 1월 25일
0

Leetcode with Python

목록 보기
1/4
post-thumbnail

leetcode link here


my try

programmiz - python string

나의 로직 흐름

  1. 문자열을 반으로 쪼갠다.
    앞에서 뒤로와 뒤에서 앞으로가 같으려면 중간지점이 있어야할 것이다.그후 인덱싱 하여 앞자리와 뒷자리를 비교한다.

  2. 위의 방법보다 훨씬 간단한 방법을 찾았다 how to reverse a string
    s[::-1] 인덱싱은 s 를 뒤집어서 나열한다. 그렇다면 reverse s == s 일 경우가 바로 palindrome 일텐데,
    문제점은

    대소문자와 특수문자를 무시한다.

추가 조건의 로직 생각해본다.

for element in s ,

if element != Upper or Lower alphanumeric , ignore.
s에 있는 요소중 "대소알파벳or 숫자" 가 아니면 무시.

요소를 iterate 해서 훝어봐도 괜찮을 것 같다.


solution

이 포스트의 솔루션 내용은 파이썬 알고리즘 인터뷰를 바탕으로 작성하였다.

솔루션1- 리스트 생성 후 isalnum()

먼저 '알파뉴메리컬' 한지 판단 을 처리할수있는 string function isalnum() 을 이용해서 alphanumerical 한지 검사한다.

string =[]
for char in s:
	if char.isalnum():
    		string.append(char.lower())

s의 element 중 isalnum() 을 만족하는 elemnt 의 경우, string []에 소문자로 바꿔서 넣어준다.

이제 리스트를 뒤집었을 때 palindrome 인지 판단 하면 된다.

리스트인 string 에 요소가 1개라도있을경우,
pop() 을 이용하여 0번째 요소가 마지막요소와 다를경우 False 를 리턴한다

python list pop() method

while len(string)>1:

	if string.pop(0) != string.pop():
    		return False

솔루션2 - 슬라이싱

먼저 lower()메소드를 이용하여 모두 소문자로 변환한다.

그다음 정규식(regular expression)을 이용해서 non-alphanumerical 한 문자들을 모두 필터링 한다.

A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
python regular expression

Python3 의 코드는 다음과 같다.

def isPalindrome(self, s:str) ->bool:

    s=s.lower()
    #아래는 파이썬 정규식 re모듈의 sub메소드
    s=re.sub('[^a-z0-9]','',s)
    
    #필터링된 s를 슬라이싱으로 뒤집는다.
    return s==s[::-1]

파이썬3의 슬라이싱은 C로 구성되어있어 처리속도가 빠르다.

profile
개발의 길을 걷자

0개의 댓글

관련 채용 정보