https://programmers.co.kr/learn/courses/30/lessons/64061
현재 뽑은 인형과 스택의 top에 있는 인형을 비교하여 같다면 제거(pop)
같지 않다면 스택에 push
#include <string>
#include <vector>
#include <stack>
using namespace std;
int solution(vector<vector<int>> board, vector<int> moves) {
int answer = 0;
stack<int> st;
st.push(-1);
for (int i = 0; i < moves.size(); i++)
{
for (int y = 0; y < board.size(); y++)
{
// 인형 하나를 뽑기
auto currentDoll = board[y][moves[i]-1];
// 뽑은 인형이 0이 아니라면?
if (currentDoll != 0)
{
// 뽑은 인형이 이전에 뽑은 인형과 같다 -> 삭제
if(currentDoll == st.top())
{
answer+=2;
st.pop();
}
// 같지 않다 -> 스택에 넣기
else
st.push(currentDoll);
// 뽑은 자리에는 0 넣기, 이전 인형은 스택 top으로 세팅
board[y][moves[i]-1] = 0;
break;
}
}
}
return answer;
}
'프로그래밍 > 알고리즘' 카테고리의 다른 글
[C/C++] 아날로그 시계 (0) | 2019.11.03 |
---|