처음에 이분탐색으로 접근했으나 논리가 맞지 않아 투포인터(중심 확장법) 으로 구현했다.
모든 위치 i를 팰린드롬의 중심으로 잡고 양쪽으로 확장하며 체크한다.
두 가지 경우를 따로 처리해야 한다.
i < size 까지 순회import java.util.*;
class Solution {
public int solution(String s) {
int answer = 0;
int size = s.length();
for (int i = 0; i < size; i++) {
// 홀수 길이
int lt1 = i - 1, rt1 = i + 1;
boolean success1 = false;
while (check(lt1, rt1, size)) {
if (s.charAt(lt1) == s.charAt(rt1)) {
lt1--; rt1++; success1 = true;
} else break;
}
int result1 = success1 ? (rt1 - 1) - (lt1 + 1) + 1 : 1;
// 짝수 길이
int lt2 = i, rt2 = i + 1;
boolean success2 = false;
while (check(lt2, rt2, size)) {
if (s.charAt(lt2) == s.charAt(rt2)) {
lt2--; rt2++; success2 = true;
} else break;
}
int result2 = success2 ? (rt2 - 1) - (lt2 + 1) + 1 : 0;
answer = Math.max(answer, Math.max(result1, result2));
}
return answer;
}
public boolean check(int lt, int rt, int n) {
if (lt < 0 || rt >= n) return false;
return true;
}
}