[백준] 1874번: 스택 수열

ByWindow·2021년 9월 7일
0

Algorithm

목록 보기
59/104
post-thumbnail

📝문제

문제에서 열심히 스택에 대해 설명해주어서 스택으로 풀었다.
계산 로직은 손으로 직접 풀 때와 비슷한데
현재 입력된 수까지 오름차순으로 스택에 PUSH하고 현재 스택의 최상단 값과 입력된 수가 같다면 POP한다. 그리고 PUSH할 때는 현재 몇 번째 수까지 PUSH를 했는지 체크하고 다음 PUSH할 때는 그 수에 +1을 한 수부터 PUSh 한다.

📌코드

package Baekjoon;

import java.util.*;
import java.io.*;

public class BOJ1874 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringBuilder sb = new StringBuilder();
        /**
         * 입력받은 숫자가 나올때까지
         * 스택에 순서대로 수를 넣는다
         * 입력받은 수가 나오면 pop한다
         *
         */
        Stack<Integer> stack = new Stack<>();
        int curInput = 0;//현재 몇 번째까지 넣었는지 기록

        for(int i = 0; i < n; i++){
            int cur = Integer.parseInt(br.readLine());
            //필요한경우 스택에 push
            for(int j = curInput+1; j <= cur; j++){
                stack.push(j);
                sb.append("+\n");
                curInput = j;
            }
            if(cur == stack.peek()){
                stack.pop();
                sb.append("-\n");
            }
        }
        System.out.println(stack.size() > 0 ? "NO" : sb.toString());
    }
}
profile
step by step...my devlog

0개의 댓글