공부하고 기록하는, 경제학과 출신 개발자의 노트

프로그래밍/코딩테스트 문제풀이

[Python] 프로그래머스. 가장 긴 팰린드롬 (Level 3)

inspirit941 2020. 7. 29. 14:32
반응형

https://programmers.co.kr/learn/courses/30/lessons/12904

 

코딩테스트 연습 - 가장 긴 팰린드롬

앞뒤를 뒤집어도 똑같은 문자열을 팰린드롬(palindrome)이라고 합니다. 문자열 s가 주어질 때, s의 부분문자열(Substring)중 가장 긴 팰린드롬의 길이를 return 하는 solution 함수를 완성해 주세요. 예를들

programmers.co.kr

홀수 / 짝수 두 개의 window를 기준으로 판별한다.

 

 

def solution(s: str):
def expand(left: int, right: int) -> str:
# 현재 left idx, right idx가 같은 문자열일 경우
# 윈도우 크기를 좌우로 1씩 넓힌다.
while left >= 0 and right <= len(s) and s[left] == s[right-1]:
left -= 1
right += 1
return s[left+1:right-1]
# 연산 필요없는 경우
if len(s) < 2 or s == s[::-1]:
return len(s)
result = ""
for i in range(len(s)-1):
result = max(result, expand(i, i+1), expand(i,i+2), key = len)
return len(result)
반응형