백준 - JAVA/재귀

[백준] 25501번 : 재귀의 귀재 _ JAVA ( 주석 설명 )

wch_s 2023. 2. 10. 23:06

1번

문자열의 Palindrome을 체크 값, 재귀 함수의 실행 횟수를 출력한다.

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

public class Main {
    static int recursion_count; //recursion 함수 호출 횟수를 구하기 위한 변수이다.

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //빠른 입력을 위해 버퍼를 이용해 입력을 받는다.
        int T = Integer.parseInt(br.readLine()); //테스트케이스 개수 T를 입력받는다.

        StringBuilder sb = new StringBuilder(); //빠른 출력을 위한 StringBuilder를 생성한다.

        for(int i=0;i<T;++i){
            String str = br.readLine(); //팰린드롬을 체크를 할 문자열을 입력받는다.
            recursion_count = 0; //테스트케이스를 반복할 때마다 0으로 초기화 한다.

            if(isPalindrome(str)) //팰린드롬이면 1, 아니면 0
                sb.append('1');
            else
                sb.append('0');

            sb.append(' ').append(recursion_count).append('\n'); //recursion 함수 호출 횟수를 더한다.
        }

        System.out.println(sb); //isPalindrome 함수의 반환값과 recursion 함수의 호출 횟수를 한 줄에 공백으로 구분하여 출력한다.
    }

    private static boolean isPalindrome(String str) {
        return recursion(str, 0, str.length()-1); //시작 인덱스와 끝 인덱스 비교를 시작으로 팰린드롬 검사를 한다.
    }

    private static boolean recursion(String str, int a, int z) {
        ++recursion_count; //함수 호출 횟수를 카운트한다.
        if(a>=z) //홀수일 때는 중간값 짝수일 때는 서로 기준을 넘어갈 때까지 모두 펠린드롬이었다면 true를 리턴한다.
            return true;
        else if(str.charAt(a)==str.charAt(z)) //시작 인덱스와 끝 인덱스를 점점 좁혀간다.
            return recursion(str, a+1, z-1);
        else //펠린드롬이 아니라면 false를 출력한다.
            return false;
    }
}