Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

forDevLife

[백준] 1343 - 폴리오미노 본문

알고리즘

[백준] 1343 - 폴리오미노

JH_Lucid 2021. 6. 14. 12:49

간단한 문제이지만, 입력 케이스 별로 처리를 하느라 조금 애를 먹었다.

 

주요 1 : 연속되는 X의 개수가 짝수일 때, 몫의 수만큼 AAAA를 출력, 나머지가 2라면 한번만 BB를 출력한다.

주요 2 : 연속되는 X의 개수가 홀수일 경우, -1을 출력하고 main 함수 리턴한다.

 

처리 1 : "."의 이전 값(arr[i-1])이 X일 경우, 세어두었던 cnt를 기준으로 출력하는 print함수를 호출한다.

처리 2 : 처음부터 .이 나오는 경우에 arr[i-1]은 outOfBoundIndex이다. 따라서 i-1>=0이라는 조건을 건다.

처리 3 : 출력 기준을 "."로 했었는데, 맨 마지막 값이 'X'일 경우에도 여태까지 쌓였던 cnt만큼 출력이 필요하다.

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


public class Main {

    static StringBuffer str = new StringBuffer();

    public static void main(String args[]) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] arr = br.readLine().toCharArray();

        int cnt = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == '.') {
                if (cnt % 2 != 0) {
                    System.out.println(-1);
                    return;
                }
                if (i - 1 >= 0 && arr[i - 1] == 'X') { // 처리 1 & 2 부분
                    print(cnt);
                    cnt = 0;
                }
                str.append(".");
            }
            if (arr[i] == 'X') {
                if (i == arr.length - 1) { // 처리 3 부분
                    if ((cnt + 1) % 2 != 0) {
                        System.out.println(-1);
                        return;
                    }
                    print(cnt + 1);
                }
                cnt++;
            }
        }
        System.out.println(str.toString());
    }

    static void print(int cnt) {
        int x_cnt = cnt / 4;
        for (int j = 0; j < x_cnt; j++) {
            str.append("AAAA");
        }
        if (cnt % 4 == 2) {
            str.append("BB");
        }
    }
}
Comments