[Java] 프로그래머스 가장 긴 팰린드롬

hyunnzl·2025년 4월 4일

프로그래머스

목록 보기
20/58
post-thumbnail

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

난이도

Level 3

문제

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

예를들면, 문자열 s가 "abcdcba"이면 7을 return하고 "abacde"이면 3을 return합니다.

제한사항

  • 문자열 s의 길이 : 2,500 이하의 자연수
  • 문자열 s는 알파벳 소문자로만 구성

내 코드

class Solution{
    public int solution(String s){
        int max = 1;
        int len = s.length();
        for(int i = 0; i < len; i++){
            max = Math.max(max, expand(i, i, s));
            max = Math.max(max, expand(i, i+1, s));
        }
        return max;
    }
    
    public int expand(int left, int right, String s){
        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            left--;
            right++;
        }
        return right - left - 1;
    }
}

0개의 댓글