[프로그래머스] 크레인 인형뽑기
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;
}
}
}
}
'프로그래머스 > 카카오' 카테고리의 다른 글
[프로그래머스] 오픈채팅방 (0) | 2020.04.02 |
---|---|
[프로그래머스] [1차] 뉴스 클러스터링 (0) | 2020.04.01 |
[프로그래머스] [1차] 다트게임 (0) | 2020.03.31 |
[프로그래머스] 문자열압축 (0) | 2020.03.30 |
[프로그래머스] 비밀지도[1차] (0) | 2020.03.25 |