board판에서 배치된 인형을 뽑아서 바구니에 담는다. 이때 바구니에 같은 인형이 배치되면 그 두개의 인형은 사라진다. 이 때 사라지는 인형의 수를 구해라
이 문제는 그냥 구조 그림 자체가 stack을 쓰라고 알려준다.
문제에서 board[][] 인덱스 0을 1로 잡고있기 때문에 해당 moves배열에 접근하는 x의 값에 --를 해준다.
import java.util.*;
class Solution {
public int solution(int[][] board, int[] moves) {
int answer = 0;
Stack<Integer> stack = new Stack<>();
for(int x : moves){
x--;
for(int i=0; i<board.length; i++){
if(board[i][x]!=0){
stack.push(board[i][x]);
while(!stack.isEmpty() && stack.size()>1){
Integer pop1 = stack.pop();
Integer pop2 = stack.pop();
if(pop1 == pop2) answer+=2;
else{
stack.push(pop2);
stack.push(pop1);
}
break;
}
board[i][x] = 0;
break;
}
}
}
return answer;
}
}