본문 바로가기

알고리즘(백준 등) 공부

SWEA 23005. 회문 만들기

주어진 길이 10^5  이하의 문자열에 대해서 원하는 곳에 x를 원하는 만큼 추가하여 회문으로 만들 수 있으면 x를 추가한 횟수를 출력하고 못 만들면 -1을 출력하는 문제이다.

 

투 포인터를 이용하여 양쪽 끝부터 중간까지 문자를 비교하면서 같으면 중간으로 포인터를 이동한다. 둘 중 하나가 x라면 다른 한 쪽에 x를 추가하면 되므로 x인 쪽의 포인터만 중간쪽으로 한 칸 이동한다. 같지 않고 둘 다 x가 아니라면 회문을 만들 수 없는 경우이다.

String str = br.readLine();
int start = 0, end = str.length()-1, count = 0;
while(end > start) {
    if(str.charAt(start) == str.charAt(end)) {
        start++;
        end--;
        continue;
    }
    if(str.charAt(start) == 'x') {
        count++;
        start++;
        continue;
    }
    if(str.charAt(end) == 'x') {
        count++;
        end--;
        continue;
    }
    sb.append("-1").append('\n');
    continue outer;
}
sb.append(count).append('\n');

 

 

결과 코드는 다음과 같다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int tc = Integer.parseInt(br.readLine());
        StringBuilder sb = new StringBuilder();
        outer: while(tc-- > 0) {
            String str = br.readLine();
            int start = 0, end = str.length()-1, count = 0;
            while(end > start) {
                if(str.charAt(start) == str.charAt(end)) {
                    start++;
                    end--;
                    continue;
                }
                if(str.charAt(start) == 'x') {
                    count++;
                    start++;
                    continue;
                }
                if(str.charAt(end) == 'x') {
                    count++;
                    end--;
                    continue;
                }
                sb.append("-1").append('\n');
                continue outer;
            }
            sb.append(count).append('\n');
        }
        br.close();
        System.out.print(sb);
    }
}

'알고리즘(백준 등) 공부' 카테고리의 다른 글

SWEA 22979. 문자열 옮기기  (0) 2026.04.20
SWEA 23003. 색상환  (0) 2026.04.20
백준 1384번: 메시지  (0) 2026.04.16
SWEA 24396. 공과 상자  (0) 2026.04.15
SWEA 24524. 레벨업  (0) 2026.04.14