박상길, 『파이썬 알고리즘 인터뷰』를 정리한 내용입니다.
https://leetcode.com/problems/valid-palindrome/
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
영문자와 숫자만 판별하기 때문에 공백과 기호는 비교하면 안된다
대소문자를 구분하지 않기 때문에 모든 영문자는 소문자로 변환하는 것이 좋다.
다음과 같이 리스트나 deque에 소문자와 숫자만 넣는다.
strs = [] #팰린드롬 판별에 사용할 리스트
for c in s: #s : input string
if c.isalnum():
strs.append(c.lower())
정규식을 사용해 문자를 필터링한다
s = s.lower()
s = re.sub('[^a-z0-9]', '', s)
while len(strs) > 1:
if strs.pop(0) != strs.pop():
return False
리스트의 pop(0)는 O(n)인데 deque의 popleft는 O(1)이기 때문에 deque를 사용하면 성능을 높일 수 있다
from collections import deque
def isPalindrome(s):
strs = deque()
for c in s:
if c.isalnum():
strs.append(c.lower())
while len(strs) > 1:
if strs.popleft() != strs.pop():
return False
input string을 소문자와 숫자로만 이루어진 문자열로 변환 후 슬라이싱 기능을 이용해 뒤집은 문자열과 비교한다
슬라이싱은 내부적으로 C로 구현되어있기때문에 속도가 훨씬 빠르다.
def isPalindrome(s):
s = s.lower()
s = re.sub('[^a-z0-9]', '', s)
return s == s[::-1]
[파이썬 알고리즘 인터뷰] 자기 자신을 제외한 배열의 곱 | 리스트, 선형 자료구조 (1) | 2023.05.24 |
---|---|
[프로그래머스] 152995. 인사고과| 정렬, 구현 | 파이썬, 소스코드, 정답 (1) | 2023.05.23 |
[SW Expert Academy] 15230. 알파벳 공부 | 문자열비교 | 파이썬, 소스코드, 정답 (2) | 2023.05.20 |
[SW Expert Academy] 15612. 체스판 위의 룩 배치 | 구현 | 파이썬, 소스코드, 정답 (0) | 2023.05.19 |
[SW Expert Academy] 16800. 구구단 걷기 | 구현 | 파이썬, 소스코드, 정답 (0) | 2023.05.18 |