1. 문제 풀이 아이디어
- 스택을 활용하여 문제를 해결할 수 있다.
2. 나의 정답 코드
class Solution {
public int solution(int[][] board, int[] moves) {
int answer = 0;
Stack<Integer>[] stack = new Stack[board[0].length];
Stack<Integer> result = new Stack<>();
for (int i = 0; i < board[0].length; i++) {
stack[i] = new Stack<>();
for (int j = board.length - 1; j >= 0; j--) {
if (board[j][i] == 0)
continue;
stack[i].push(board[j][i]);
}
}
for (int i = 0; i < moves.length; i++) {
if (stack[moves[i] - 1].isEmpty())
continue;
int cur = stack[moves[i] - 1].pop();
if (!result.isEmpty() && result.peek() == cur) {
result.pop();
answer += 2;
} else {
result.push(cur);
}
}
return answer;
}
}
3. 정리
- 각 열을 스택 배열에 저장한다.
moves
를 순회하며 해당 열에서 값을 꺼내cur
에 저장한다.
result
스택의 최상단과cur
이 같으면 값을 꺼내고 결과값을 2 증가시킨다.
- 다르면
cur
을result
스택에 넣는다.
- 이 과정을 반복하여 결과값을 구한다.
Share article