곰퓨타의 SW 이야기

[프로그래머스 level3 가장 긴 팰린드롬] 문자열 파싱하기 본문

TIL/프로그래머스

[프로그래머스 level3 가장 긴 팰린드롬] 문자열 파싱하기

곰퓨타 2021. 9. 25. 11:00

해결해야하는 문제는 다음과 같았다.

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

 

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

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

programmers.co.kr

 

아이디어는 다음과 같다.

 

 

아이디어를 바탕으로 작성한 코드는 다음과 같다.

def solution(s):
    answer = len(s)
    len_s = len(s)
    while answer > 0:
        for i in range(len_s-answer+1):
            temp_s = s[i:i+answer]
            for j in range(answer//2):
                if temp_s[j] != temp_s[answer-j-1] :
                    break
            else :
                return answer
        answer -= 1

    return answer
Comments