백준

최현주·2024년 1월 23일
0
25501번 재귀의 귀재

참고사이트 : https://travelerfootprint.tistory.com/260

import java.util.*;

public class Main{
	
    static int result;
    public static int recursion(String s, int l, int r){
    	result++;
        if(l >= r) return 1;
        else if(s.charAt(l) != s.charAt(r)) return 0;
        else return recursion(s, l+1, r-1);
    }
    
    public static int isPalindrome(String s){
        return recursion(s, 0, s.length()-1);
    }
    
    public static void main(String[] args){
    	Scanner sc = new Scanner(System.in);
    	int T = sc.nextInt();
    	for(int i = 0; i < T; i++) {
    		result = 0;
    		System.out.println(isPalindrome(sc.next()) + " " + result);
    	}
    	sc.close();
    }
}

recursion 함수의 호출 횟수를 전역 변수를 활용하여 간단하게 해결할 수 있는데 전역 변수 선언 후 문자열을 입력하기 전에 0으로 초기화를 해준 뒤 recursion 함수의 첫 줄에 1증가시키면 이 문제는 쉽게 해결된다

profile
갓벽한 개발자

0개의 댓글