728x90
📌오늘의 학습 키워드
- 투포인터
- 문자열을 처음과 끝에서부터 포인터로 살펴보면서 회문인지, 유사회문인지 확인하는 알고리즘
✨공부한 내용 본인의 언어로 정리하기
- 처음에는 while문을 이용한 투포인터로 해결하려고 했다.
- 유사회문을 찾을 때 만약 한칸을 띄었을 경우 다른 포인터 값과 일치하면 한칸을 띄고 진행했다.
- 하지만 abxxbxa 의 경우 앞 포인터를 띄우거나 뒤 포인터를 띄웠을 때 모두 2번 조건을 만족하고, 둘 다 진행해 봐야 답을 찾을 수 있었다.
- 따라서 while문이 아닌 어떤 문자를 띄우든 답을 확인해볼 수 있도록 재귀로 바꿔서 풀었다.
[🤓문제 해결 코드]
더보기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
static int N;
static String str;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
N = Integer.parseInt(br.readLine());
for(int i=0; i<N; i++) {
str = br.readLine();
int start = 0;
int end = str.length()-1;
int chance = 2;
chance = Math.min(chance, find(start, end, 0));
sb.append(chance + "\n");
}
System.out.println(sb);
}
static int find(int start, int end, int chance) {
if(start >= end) {
if(chance > 1)
chance = 2;
return chance;
}
if(str.charAt(start) == str.charAt(end)) {
return find(start+1, end-1, chance);
}
int ans = 2;
if(chance == 0) {
if(str.charAt(start+1) == str.charAt(end)) {
ans = Math.min(ans, find(start+1, end, chance+1));
}
if(str.charAt(start) == str.charAt(end-1)) {
ans = Math.min(ans, find(start, end-1, chance+1));
}
}
return ans;
}
}
728x90
'코딩테스트' 카테고리의 다른 글
백준 1719 택배 자바 (0) | 2025.02.20 |
---|---|
백준 2342 Dance Dance Revolution 자바 (1) | 2025.02.19 |
백준 11404 플로이드 (0) | 2025.02.18 |
삼성 SDS 2025년도 상반기 알고리즘 특강 기록 (0) | 2025.02.18 |
백준 9663 N-Queen (0) | 2025.02.03 |