250712 #15164번_제보

Jongleee·2025년 7월 12일
0

TIL

목록 보기
957/970
public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input = br.readLine();

        long result = countPalindromes(transform(input));

        System.out.println(result);
    }

    private static String transform(String input) {
        StringBuilder sb = new StringBuilder("#");
        for (char ch : input.toCharArray()) {
            sb.append(ch).append("#");
        }
        return sb.toString();
    }

    private static long countPalindromes(String s) {
        int length = s.length();
        int[] radius = new int[length];
        int right = 0, center = 0;
        long total = 0;

        for (int i = 0; i < length; i++) {
            if (i <= right) {
                radius[i] = Math.min(radius[2 * center - i], right - i);
            }

            while (i - radius[i] - 1 >= 0 &&
                    i + radius[i] + 1 < length &&
                    s.charAt(i - radius[i] - 1) == s.charAt(i + radius[i] + 1)) {
                radius[i]++;
            }

            if (i + radius[i] > right) {
                right = i + radius[i];
                center = i;
            }

            total += (radius[i] + 1) / 2;
        }

        return total;
    }

출처:https://www.acmicpc.net/problem/16163

0개의 댓글