OJ

[BOJ] 17609 회문 (JAVA)

P3PP4 2023. 2. 12. 10:00

https://www.acmicpc.net/problem/17609

 

17609번: 회문

각 문자열이 회문인지, 유사 회문인지, 둘 모두 해당되지 않는지를 판단하여 회문이면 0, 유사 회문이면 1, 둘 모두 아니면 2를 순서대로 한 줄에 하나씩 출력한다.

www.acmicpc.net

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) throws Exception {

        int T = Integer.parseInt(br.readLine());

        for (int tc = 0; tc < T; tc++) {
            sb.append(pal(br.readLine(), 0)).append("\n");
        }

        System.out.print(sb.toString());

    }

    static int pal(String s, int isPalindrome) {

        int head = 0;
        int tail = s.length() - 1;
        int left = 2;
        int right = 2;

        while (head < tail && isPalindrome < 2) {

            if (s.charAt(head) != s.charAt(tail)) {

                if (++isPalindrome == 2 || tail - head < 2) return isPalindrome;

                if (s.charAt(head) == s.charAt(tail - 1)) left = pal(s.substring(head, tail), isPalindrome);
                if (s.charAt(head + 1) == s.charAt(tail)) right = pal(s.substring(head + 1, tail + 1), isPalindrome);

                return Math.min(left, right);

            }

            head++;
            tail--;

        }

        return isPalindrome;

    }

}