본문 바로가기
Java/AlgorithmPS

백준) 스택 수열(1874번)

by NH_club 2023. 9. 22.
 

1874번: 스택 수열

1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.

www.acmicpc.net

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

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int n = Integer.parseInt(br.readLine());

        Stack<Integer> stack = new Stack<>();
        int current = 1;

        for (int i = 0; i < n; i++) {
            int value = Integer.parseInt(br.readLine());

            while (current <= value) {
                stack.push(current++);
                sb.append("+\n");
            }

            if (stack.peek() == value) {
                stack.pop();
                sb.append("-\n");
            } else {
                System.out.println("NO");
                return;
            }
        }

        System.out.println(sb.toString());
    }
}

혼자서 못 풀었음

Stack의 이해도보단 문제 해결 능력이 부족하다 판단.

문제를 많이 풀어봐야 할 듯

'Java > AlgorithmPS' 카테고리의 다른 글

백준) 단어 뒤집기2(17413번)  (0) 2023.09.23
백준) 과제는 끝나지 않아(17952번)  (0) 2023.09.23
백준) 세로읽기(10798번)  (0) 2023.09.20
백준) 팰린드롬수(1259번)  (0) 2023.09.20
백준) 2007년(1924번)  (0) 2023.09.19