forDevLife
[백준] 1343 - 폴리오미노 본문
간단한 문제이지만, 입력 케이스 별로 처리를 하느라 조금 애를 먹었다.
주요 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");
}
}
}
'알고리즘' 카테고리의 다른 글
[백준] 1018 - 체스판 다시 칠하기 (0) | 2021.06.14 |
---|---|
[백준] 1417 - 국회의원 선거 (0) | 2021.06.14 |
[백준] 17224 - APC는 왜 서브태스크 대회가 되었을까? (0) | 2021.06.13 |
[백준] 2839 - 설탕 배달 (0) | 2021.06.11 |
[백준] 2828 - 사과 담기 게임 (0) | 2021.06.09 |
Comments