๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[Baekjoon] 28278. ์Šคํƒ 2/Java - Silver4

by The Future Engineer, Lucy 2024. 9. 28.
728x90
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

https://www.acmicpc.net/problem/28278

๐Ÿ“Œ์œ ํ˜•

์Šคํƒ

โœ๐Ÿปํ’€์ด

1๋ฒˆ ๋ช…๋ น์–ด์˜ ๊ณต๋ฐฑ ๋’ค ์˜ค๋Š” ์ˆซ์ž๋Š” ์Šคํƒ์— push.
2๋ฒˆ ๋ช…๋ น์–ด ์ž…๋ ฅ ์‹œ stack.empty()๋ผ๋ฉด -1 ์•„๋‹ˆ๋ผ๋ฉด stack.pop()์œผ๋กœ ์Šคํƒ์—์„œ ๋นผ๋Š” ๋™์‹œ์— ์ถœ๋ ฅ.
3๋ฒˆ ๋ช…๋ น์–ด ์ž…๋ ฅ ์‹œ stack.size()๋กœ ํฌ๊ธฐ ์ถœ๋ ฅ.
4๋ฒˆ ๋ช…๋ น์–ด ์ž…๋ ฅ ์‹œ stack.empty()๋ผ๋ฉด 1 ์•„๋‹ˆ๋ฉด 0 ์ถœ๋ ฅ.
5๋ฒˆ ๋ช…๋ น์–ด ์ž…๋ ฅ ์‹œ stack.empty()๋ผ๋ฉด -1 ์•„๋‹ˆ๋ฉด stack.peek()์œผ๋กœ stack์˜ top ๊ฐ’ ์ถœ๋ ฅ.

๐Ÿ’ป์ฝ”๋“œ

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

public class Main {

    static int n;
    static BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); // ์ž…๋ ฅ

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

        n = Integer.parseInt(r.readLine());

        Stack<Integer> stack = new Stack<>();

        StringTokenizer st;
        while (n-- > 0) {
            st = new StringTokenizer(r.readLine());
            String c = st.nextToken();
            if (c.equals("1")) {
                stack.push(Integer.parseInt(st.nextToken()));
            } else if (c.equals("2")) {
                System.out.println(stack.empty() ? -1 : stack.pop());
            } else if (c.equals("3")) {
                System.out.println(stack.size());
            } else if (c.equals("4")) {
                System.out.println(stack.empty() ? 1 : 0);
            } else {
                System.out.println(stack.empty() ? -1 : stack.peek());
            }
        }
    }
}

๐Ÿ’ก์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ ๋œ ๋‚ด์šฉ

**BufferWriter, BufferReader**
- ๊ธฐ์กด์˜ Scanner๋‚˜ System.out ๋ณด๋‹ค ๋น ๋ฅด๊ฒŒ ์ˆ˜ํ–‰ ๊ฐ€๋Šฅ.
- IOException ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ํ•„์š”. ํ•จ์ˆ˜์—์„œ throws๋กœ ์ฒ˜๋ฆฌํ•˜๊ฑฐ๋‚˜ try catch๋ฌธ ํ•„์š”.
- BufferWriter.write()๋Š” ๊ด„ํ˜ธ ์•ˆ์˜ ๊ฐ’์„ ์ถœ๋ ฅํ•จ. ์ด ๋•Œ, ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ char๋‚˜ string์„ ๋ฐ›๊ธฐ ๋•Œ๋ฌธ์— ์ˆซ์ž๋ฅผ
	์ถœ๋ ฅํ•˜๊ณ  ์‹ถ์œผ๋ฉด, String.valueOf๋กœ ๊ฐ์‹ธ์•ผ ํ•จ.

**StringTokenizer**
- ๊ณต๋ฐฑ์œผ๋กœ ๊ฐ’์„ ๊ตฌ๋ถ„ํ•˜๋Š” ๊ฒฝ์šฐ, StringTokenizer๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋น ๋ฅด๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์Œ.
- bufferreader.readLine().split(" ")์œผ๋กœ๋„ ๊ฐ€๋Šฅํ•˜๋‚˜ ๋น„๊ต์  ๋Š๋ฆผ.
728x90
๋ฐ˜์‘ํ˜•