[백준] 25501번 : 재귀의 귀재 - JAVA
2024. 11. 14. 13:49 - DoosanBaek
문제 분석 : 펠린드롬 함수의 반환값과 재귀 함수의 호출 횟수를 구한다.
제약 조건 :
- 첫째 줄에 테스트 케이스의 개수 T가 주어진다.
- 둘째 줄 부터 T개의 줄에 알파벳 대문자로 구성된 문자열 S가 주어진다.
의사결정 :
- isPalindrome 함수의 반환 값 구하기
- 재귀 호출 실행 횟수 카운트 구하기
- 한줄에 출력
package com.doosane.study01.week01.bronze;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Week02_01_BOJ_25501 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(reader.readLine().trim()); // 테스트 케이스의 개수
StringBuilder output = new StringBuilder();
for (int i = 0; i < T; i++) {
String S = reader.readLine().trim();
Result result = isPalindrome(S);
output.append(result.isPalindrome).append(" ").append(result.callCount).append("\n");
}
System.out.print(output.toString()); // 한 번에 출력
}
// 재귀 호출 결과
static class Result {
int isPalindrome;
int callCount;
Result(int isPalindrome, int callCount) {
this.isPalindrome = isPalindrome;
this.callCount = callCount;
}
}
// 팰린드롬 검사 함수
public static Result isPalindrome(String s) {
return recursion(s, 0, s.length() - 1, 1);
}
// 재귀 함수
public static Result recursion(String s, int l, int r, int count) {
if (l >= r) {
return new Result(1, count);
} else if (s.charAt(l) != s.charAt(r)) {
return new Result(0, count);
} else {
return recursion(s, l + 1, r - 1, count + 1);
}
}
}
'알고리즘' 카테고리의 다른 글
[백준] 26041번 : 비슷한 전화번호 표시 - JAVA (0) | 2024.11.15 |
---|---|
[백준] 2675번 : 문자열 반복 - JAVA (1) | 2024.11.15 |
[백준] 9184번 : 신나는 함수 실행 - JAVA (0) | 2024.11.14 |
[백준] 10994번 : 별 찍기 - JAVA (0) | 2024.11.14 |
[백준] 24416번 : 알고리즘 수업 피보나치 수 1 - JAVA (0) | 2024.11.14 |
[백준] 2167번 : 2차원 배열의 합 - JAVA (0) | 2024.11.13 |
[백준] 2018번 : 수들의 합 5 - JAVA (0) | 2024.11.13 |
[백준] 17207번 : 돌려막기 - JAVA (0) | 2024.11.13 |