윤재에요 2024. 3. 4. 16:06

https://www.acmicpc.net/problem/17609

 

17609번: 회문

각 문자열이 회문인지, 유사 회문인지, 둘 모두 해당되지 않는지를 판단하여 회문이면 0, 유사 회문이면 1, 둘 모두 아니면 2를 순서대로 한 줄에 하나씩 출력한다.

www.acmicpc.net

 

import java.util.*;
import java.io.*;
public class Main
{   

    public static boolean isPalindrome(String word, int left, int right,boolean is_remove){
        while(left<right && left<word.length() && right>=0){
            if(word.charAt(left)==word.charAt(right)){
                left++;
                right--;
                continue;
            }else{
                if(is_remove){
                    return false;
                }else{
                    return isPalindrome(word, left+1,right,true) || isPalindrome(word, left,right-1, true);
                    
                }
            }
        }
        return true;
    }
    public static int solution(String word){
        if(isPalindrome(word,0,word.length()-1,true)){
            return 0;
        }
        if(isPalindrome(word,0,word.length()-1,false)){
            return 1;
        }
        return 2;
    }
    
	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 word = br.readLine();
		    bw.write(solution(word)+"\n");
		}
	
		bw.flush();
	}
}
import java.util.Arrays;
import java.util.Scanner;

class Main
{
    static boolean isPalindrome(char[] str, int l, int r) {
        while (l <= r) {
            if (str[l] != str[r]) return false;
            l++;
            r--;
        }
        return true;
    }

    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();
        while (T-- > 0) {
            char[] str = sc.next().toCharArray();
            int ans = 0;
            int l = 0, r = str.length - 1;
            while (l <= r) {
                if (str[l] != str[r]) {
                    if (isPalindrome(str, l + 1, r) || isPalindrome(str, l, r - 1)) ans = 1;
                    else ans = 2;
                    break;
                }
                l++;
                r--;
            }
            System.out.println(ans);
        }
    }
}