[백준] 10828번 : 스택 - JAVA [자바]

2022. 6. 13. 01:44·알고리즘/백준

문제

문제 링크 : https://www.acmicpc.net/problem/10828


수도코드 작성

주어진 명령어 그대로 if문으로 구현하면 될 것 같았다.

 

3가지로 작성을 해보았다.

1. Scanner 이용 (시간초과)

2. BufferedReader + System.out.printf 이용 (코드가 제일 짧음)

3. BufferedReader + BufferedWriter 이용


작성한 코드

1. Scanner 이용

import java.io.*;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> queue = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        for(int i=0; i<N; i++){
            String command = sc.next();
            if ("push".equals(command)) {
                queue.add(sc.nextInt());
            }
            if ("top".equals(command)){
                if(queue.size()==0){
                    System.out.println(-1);
                }else {
                    System.out.println(queue.get(queue.size() - 1));
                }
            }
            if ("size".equals(command)){
                System.out.println(queue.size());
            }
            if ("empty".equals(command)){
                if(queue.size()==0){
                    System.out.println(1);
                }
                else{
                    System.out.println(0);
                }
            }
            if("pop".equals(command)){
                if(queue.size()==0){
                    System.out.println(-1);
                }
                else {
                    int A = queue.get(queue.size()-1);
                    queue.remove(queue.size()-1);
                    System.out.println(A);
                }
            }
        }
    }
}

2. BufferedReader + System.out.printf 이용

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        ArrayList<Integer> queue = new ArrayList<>();
        int N = Integer.parseInt(bf.readLine());
        for(int i=0; i<N; i++){
            String[] command = bf.readLine().split(" ");
            if ("push".equals(command[0])) {
                queue.add(Integer.parseInt(command[1]));
            }
            if ("top".equals(command[0])){
                if(queue.size()==0){
                    System.out.println(-1);
                }else {
                    System.out.println(queue.get(queue.size() - 1));
                }
            }
            if ("size".equals(command[0])){
                System.out.println(queue.size());
            }
            if ("empty".equals(command[0])){
                if(queue.size()==0){
                    System.out.println(1);
                }
                else{
                    System.out.println(0);
                }
            }
            if("pop".equals(command[0])){
                if(queue.size()==0){
                    System.out.println(-1);
                }
                else {
                    int A = queue.get(queue.size()-1);
                    queue.remove(queue.size()-1);
                    System.out.println(A);
                }
            }
        }
    }
}

3. BufferedReader + BufferedWriter 이용

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        ArrayList<Integer> queue = new ArrayList<>();
        int N = Integer.parseInt(bf.readLine());
        for(int i=0; i<N; i++){
            String[] command = bf.readLine().split(" ");
            if ("push".equals(command[0])) {
                queue.add(Integer.parseInt(command[1]));
            }
            if ("top".equals(command[0])){
                if(queue.size()==0){
                    bw.write("-1");
                }else {
                    bw.write(Integer.toString(queue.get(queue.size() - 1)));
                }
                bw.newLine();
                bw.flush();
            }
            if ("size".equals(command[0])){
                bw.write(Integer.toString(queue.size()));
                bw.newLine();
                bw.flush();
            }
            if ("empty".equals(command[0])){
                if(queue.size()==0){
                    bw.write("1");
                }
                else{
                    bw.write("0");

                }
                bw.newLine();
                bw.flush();
            }
            if("pop".equals(command[0])){
                if(queue.size()==0){
                    bw.write("-1");

                }
                else {
                    int A = queue.get(queue.size()-1);
                    queue.remove(queue.size()-1);
                    bw.write(Integer.toString(A));
                }
                bw.newLine();
                bw.flush();
            }
        }
        bw.close();
    }
}

 

 


보완할 점 / 헷갈린 점

처음에 스캐너로 했을 때 시간초과가 떠서 결국에는 BufferedReader을 사용하는 법을 공부를 했다.

출력을 BufferedWriter로 하는 게 좋다고 해서 하는데 자꾸 이상한 출력이 나와서 알아보니까 int형이여서 출력이 안되는 것이였다. 그래서 Integer.toString을 사용해서 모든 int들을 String으로 바꾸고 BufferedWriter을 사용하였다.

 

빠른 시일 내에 BufferedReader, BufferedWriter 도 블로깅을 해둬야겠다.

 

 

 

저작자표시 (새창열림)

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 18258번 : 큐2 - JAVA [자바]  (0) 2022.06.15
[백준] 2164번 : 카드2 - JAVA [자바]  (0) 2022.06.14
[백준] 1037번 : 약수 - JAVA [자바]  (0) 2022.06.09
[백준] 1712번 : 손익분기점 - JAVA [자바]  (0) 2022.06.07
[백준] 1152번 : 단어의 개수 - JAVA [자바]  (0) 2022.06.07
'알고리즘/백준' 카테고리의 다른 글
  • [백준] 18258번 : 큐2 - JAVA [자바]
  • [백준] 2164번 : 카드2 - JAVA [자바]
  • [백준] 1037번 : 약수 - JAVA [자바]
  • [백준] 1712번 : 손익분기점 - JAVA [자바]
DevelopJJong
DevelopJJong
기록에서 기억까지
  • DevelopJJong
    기록에서 기억까지
    DevelopJJong
  • 전체
    오늘
    어제
    • 분류 전체보기 (63)
      • 프로젝트 (1)
        • 팀 프로젝트 (0)
        • 토이프로젝트 (1)
        • 디스코드 봇 개발 (0)
      • Web (8)
        • Spring (5)
        • Server (1)
      • Knowledge (0)
        • 자료구조 (0)
        • 디자인 패턴 (0)
        • 개발 지식 (0)
      • DBMS (2)
        • Oracle (2)
        • MySQL (0)
      • 알고리즘 (25)
        • 알고리즘 기초 (1)
        • 백준 (22)
        • 프로그래머스 (2)
        • 코드업 (0)
      • Programming Language (9)
        • Java (9)
        • Python (0)
      • 이론 공부 (4)
        • 자료구조 (0)
        • 컴퓨터과학(CS) (1)
        • 이산수학 (0)
        • 네트워크 (3)
      • Tool (8)
        • IntelliJ (6)
        • Git (1)
        • etc. (1)
      • 일상 (0)
        • 맛집 리뷰 (0)
        • 소소한 이야기 (0)
      • 독서 후기 (0)
      • etc. (2)
      • TIL (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • GitHub
  • 공지사항

    • 쫑이가 공부하는 공간 (광고 및 수익창출 X)
  • 인기 글

  • 태그

    네트워크 #LAN #랜선 #WAN #근거리 통신망 #원거리 통신망 #인터넷 #네트워크 공부 #프로토콜 뜻 #프로토콜
    생성자만드는법#생성자단축키#인텔리제이
    인터넷 뜻
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
DevelopJJong
[백준] 10828번 : 스택 - JAVA [자바]
상단으로

티스토리툴바