

접근법 : 팰린드롬 문제를 조금 응용해서 풀면 된다.
회문 : 'abba'나 'reviver' 처럼 앞 뒤 방향이 같은 순서의 문자로 구성된 문자열이다.
유사 회문 : 한 문자를 삭제하면 회문이 된다.
투포인터를 이용해서 회문인지를 구하고, 회문이 아니라면 유사회문인지 확인한다.
<회문 확인>
private static boolean isPalindrome(String str, int left, int right) {
while (left < right) {
if (str.charAt(left) == str.charAt(right)) {
left++;
right--;
} else {
return false;
}
}
return true;
}
<유사 회문 확인>
private static boolean isPseudoPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return isPalindrome(str, left + 1, right) || isPalindrome(str, left, right - 1);
}
left++;
right--;
}
return false;
}
<출력 부분>
for (int i = 0; i < n; i++) {
String str = br.readLine();
if (isPalindrome(str, 0, str.length() - 1)) {
bw.write(0 + "\n");
} else if (isPseudoPalindrome(str)) {
bw.write(1 + "\n");
} else {
bw.write(2 + "\n");
}
}
bw.flush();
bw.close();
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
String str = br.readLine();
if (isPalindrome(str, 0, str.length() - 1)) {
bw.write(0 + "\n");
} else if (isPseudoPalindrome(str)) {
bw.write(1 + "\n");
} else {
bw.write(2 + "\n");
}
}
bw.flush();
bw.close();
}
private static boolean isPalindrome(String str, int left, int right) {
while (left < right) {
if (str.charAt(left) == str.charAt(right)) {
left++;
right--;
} else {
return false;
}
}
return true;
}
private static boolean isPseudoPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return isPalindrome(str, left + 1, right) || isPalindrome(str, left, right - 1);
}
left++;
right--;
}
return false;
}
}