본문 바로가기

백준 문제풀기/JAVA

[백준 25501 JAVA 자바] 재귀의 귀재

각 케이스마다 isPallindrome 함수의 반환값과 

recursion 함수의 '호출 횟수'를 출력합시다

 

함수의 호출 횟수를 출력하기 위해선

static int count = 0;으로 정의하고

recursion함수 내부에 count++를 넣어주면

recursion함수가 몇번 호출되는지 계산할 수 있습니다

 

코드입니다

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

public class Main {
	
	static int count=0; // 호출 횟수를 계산합니다

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        
        StringBuilder sb = new StringBuilder();
        
        for(int i=0;i<n;i++) {
        	String str = br.readLine();
        	
        	sb.append(isPalindrome(str)+" "+count+'\n'); // isPalindrome 함수의 출력값과 호출횟수를 sb에 저장합니다
        	count=0;
        }
        System.out.println(sb);
    }
    
    public static int isPalindrome(String s){
        return recursion(s, 0, s.length()-1);
    }
    
    public static int recursion(String s, int l, int r){
    	count++; // recursion함수의 호출 횟수를 계산하는 부분입니다
        if(l >= r) return 1;
        else if(s.charAt(l) != s.charAt(r)) return 0;
        else return recursion(s, l+1, r-1);
    }    
}