백준 10828 : 스택 (Java)

liliili·2023년 2월 7일

백준

목록 보기
186/214

본문 링크

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

public class Main {
    public static void main(String[] args) throws IOException {
        Stack<Integer> stack = new Stack<>();

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

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

        for (int i = 0 ; i < N ; i++) {
            String str = br.readLine();
            if (str.contains("push"))
            {
                String[] k = str.split(" ");
                stack.push(Integer.parseInt(k[1]));
            }
            else if (str.equals("pop")) {
                if (stack.empty()) {
                    bw.write("-1\n");
                }
                else {
                    bw.write(stack.peek()+"\n");
                    stack.pop();
                }
            }
            else if (str.equals("size")) {
                bw.write( stack.size()+"\n");
            }
            else if (str.equals("empty")) {
                if (stack.empty()) {
                    bw.write("1\n");
                }
                else {
                    bw.write("0\n");
                }
            }
            else if (str.equals("top")) {
                if (stack.empty()) {
                    bw.write("-1\n");
                }
                else {
                    bw.write(stack.peek()+"\n");
                }
            }
        }

        bw.flush();
    }
}

📌 어떻게 접근할 것인가?

자료구조의 기본인 스택 기초 문제입니다.

push 를 입력받을때는 정수도 입력받아야 하기 때문에 str 을 한 줄 입력받고

str.contains("push") 를 통해 push 문자가 있는지 체크 후에

String[] k = str.split(" ");
stack.push(Integer.parseInt(k[1]));

위와같이 공백을 기준으로 push 문자와 정수를 분리한 후에 정수를 push 해주었습니다.

나머지 부분은 문제에서 주어지는 조건에 따라 그대로 구현하시면 됩니다.

0개의 댓글