[프로그래머스] 크레인 인형뽑기 게임 Java

dustle·2023년 3월 27일
1

크레인 인형뽑기 게임

Stack이 후입선출이기 때문에 Stack을 들어오는 배열만큼 초기화 시켜 푸는 방법으로 풀었는데, 배열로 하는 것이 더 효율적인 것 같습니다.

import java.util.Stack;

class Solution {
    public int solution(int[][] board, int[] moves) {
        int answer = 0;
        int n = board.length;
        int m = board[0].length;

        Stack<Integer> stack[] = new Stack[m];
        Stack<Integer> rsl = new Stack<>();
        for(int i = 0; i<m; i++) stack[i] = new Stack<>();

        for(int i = n-1; i>=0; --i){
            for(int j=0; j<m; j++)
                if(board[i][j] != 0) stack[j].push(board[i][j]);
        }

        for(int move : moves){
            if(stack[move-1].isEmpty()) continue;
            int doll = stack[move-1].pop();
            if(!rsl.isEmpty() && rsl.peek() == doll){
                rsl.pop();
                answer += 2;
            }
            else rsl.push(doll);
        }
        return answer;
    }
}

0개의 댓글