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

2020. 4. 1. 13:08프로그래머스/카카오

import java.util.*;

class Solution {
    public int solution(int[][] board, int[] moves) {
        int answer = 0;
        
        Stack<Integer> s = new Stack<>();
        
        for(int i=0; i<moves.length; i++){
            for(int j=0; j<board.length; j++){
                if(board[j][moves[i]-1] !=0){
                    if(s.isEmpty()){
                        s.push(board[j][moves[i]-1]);
                        board[j][moves[i]-1]=0;
                        break;
                    }else{
                    if(s.peek()!=board[j][moves[i]-1]){
                        s.push(board[j][moves[i]-1]);
                        board[j][moves[i]-1]=0;
                        break;
                    }
                    else{
                        answer +=2;
                        s.pop();
                        board[j][moves[i]-1]=0;
                        break;
                    }
                    }
                } 
            }
            
        }
        return answer;
    }
}

두번째 풀 때는 좀더 보기 좋게 로직을 메서드로 분리하였다.

 

import java.util.*;

class Solution {
    Stack<Integer> basket = new Stack<>();
    
    public int solution(int[][] board, int[] moves) {
        int answer = 0;
        int boardLength = board.length;
        
        for (int i=0; i<moves.length; i++) {
            for (int j=0; j<boardLength; j++) {
                if (board[j][moves[i]-1]!=0) {
                    int grapedDoll = board[j][moves[i]-1];
                    board[j][moves[i]-1] = 0;
                    answer += updateBasket(grapedDoll);   
                    break;
                } 
            }
        }
        return answer;
    }
    private int updateBasket(int grapedDoll) {
        if (basket.isEmpty()) {
            basket.push(grapedDoll);
            return 0;
        }else{
            if (basket.peek()==grapedDoll) {
                basket.pop();
                return 2;
            }else{
                basket.push(grapedDoll);
                return 0;
            }
        }   
    } 
}