BOJ 1874번 스택수열

|

스택수열


package BOJ;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

/**
 * BOJ 1874( https://www.acmicpc.net/problem/1874 )
 */

public class StackSequence {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int[] a = new int[n];
        for (int i = 0; i < a.length; i++)
            a[i] = Integer.parseInt(br.readLine());
        solve(a);

    }

    private static void solve(int[] a) {
        int n = a.length;
        Stack<Integer> stack = new Stack<>();
        int curIdx = 0;
        StringBuilder sb = new StringBuilder();

        for (int x : a) {
            if(x > curIdx){
                while(x > curIdx){
                    stack.push(++curIdx);
                    sb.append("+\n");
                }
                stack.pop();
                sb.append("-\n");
            } else {
                // stack.peek() != x
                // -> 예를 들어 stack[1,2,3],x=2이면 3을 pop()해야 2를 꺼낼 수 있다.
                // 3을 pop()하면 3을 출력할 수 없으므로 해당 조건이 필요하다.
                if(stack.peek() != x){
                    System.out.println("NO");
                    return;
                }
                stack.pop();
                sb.append("-\n");
            }
        }
        System.out.println(sb.toString());
    }
}