
실제 시험 응시했을 때도 코드 꼬여서 못 풀고, 재시도 했을 때도 쉽게 풀지 못한 문제다..
remove()와 undo()를 수행할 때만 currentSize와 currentRow를 조정하면 되는데, up(), down()을 수행할 때도 currentRow를 어떻게 조정할지 고민하느라 엄청 꼬였었다.
그리고, buildAnswer도 StringBuilder의 insert() 메서드를 몰라서 한참 헤맸다..
암튼 이렇게 간단하게 풀 수 있는 문제라니, 역시 코드를 쓰고 시작하기 보다는 설계를 잘 해놓고 구현을 시작하는게 중요하다는 것을 느낄 수 있었다.
import java.util.*;
class Solution {
private static final String UP = "U";
private static final String DOWN = "D";
private static final String REMOVE = "C";
private static final String UNDO = "Z";
private int currentRow;
private int currentSize;
private Stack<Integer> removed = new Stack<>();
public String solution(int n, int k, String[] inputs) {
currentRow = k;
currentSize = n;
for (String input : inputs) {
String command = input.substring(0, 1);
switch (command) {
case UP:
up(Integer.parseInt(input.substring(2)));
break;
case DOWN:
down(Integer.parseInt(input.substring(2)));
break;
case REMOVE:
remove();
break;
case UNDO:
undo();
break;
}
}
return buildAnswer();
}
private void up(int count) {
currentRow -= count;
}
private void down(int count) {
currentRow += count;
}
private void remove() {
removed.push(currentRow);
currentSize--;
if (currentRow == currentSize) {
currentRow--;
}
}
private void undo() {
int row = removed.pop();
currentSize++;
if (row <= currentRow) {
currentRow++;
}
}
private String buildAnswer() {
StringBuilder sb = new StringBuilder();
for (int i=0 ; i<currentSize ; i++) {
sb.append("O");
}
while (!removed.isEmpty()) {
sb.insert(removed.pop(), "X");
}
return sb.toString();
}
}