반응형
https://programmers.co.kr/learn/courses/30/lessons/12904
코딩테스트 연습 - 가장 긴 팰린드롬
앞뒤를 뒤집어도 똑같은 문자열을 팰린드롬(palindrome)이라고 합니다. 문자열 s가 주어질 때, s의 부분문자열(Substring)중 가장 긴 팰린드롬의 길이를 return 하는 solution 함수를 완성해 주세요. 예를들
programmers.co.kr

홀수 / 짝수 두 개의 window를 기준으로 판별한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 백준 11066. 파일 합치기 (0) | 2020.08.03 |
---|---|
[Python] LeetCode 42. Trapping Rain Water (0) | 2020.07.30 |
[Python] 백준 3109. 빵집 (0) | 2020.07.27 |
[Python] 백준 2458. 키 순서 (0) | 2020.07.24 |
[Python] 백준 9461. 파도반 수열 (0) | 2020.07.23 |