Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

JAVA Developer Training

4. 10828번 스택 ( java ) 본문

백준 알고리즘

4. 10828번 스택 ( java )

Romenest 2021. 8. 30. 22:21

 

package com.example;

import java.util.Scanner;

public class training {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int a = scanner.nextInt(); // 명령의 수

        int[] arr = new int[a]; // 명령의 수만큼의 크기 배열 선언
        int top = -1; // 최상단 정보
        String string;

        for (int i = 0; i < a; i++) {
            string = scanner.next();

            if (string.equals("push")) { // push 받을시
                top++; // 배열 index 1증가
                arr[top] = scanner.nextInt(); // 배열의 최상위에 push 다음 오는 int 를 받아 넣음

            } else if (string.equals("pop")) { // pop 받을시
                if (top == -1) { // 최상단에 아무것도 없을시 -1
                    System.out.println("-1");
                } else { // 배열에 수가 들어있다면 최상단의 수를 불러옴
                    System.out.println(arr[top]);
                    top--; // 그리고 다시 배열의 index 1 감소
                }
            } else if (string.equals("size")) { // 배열의 크기는 index로 0개일떈 -1 이니 +1 시켜 0으로만듬
                System.out.println(top + 1);
            } else if (string.equals("empty")) { // empty는 단순히 if구문 사용
                if (top == -1) {
                    System.out.println("1");
                } else {
                    System.out.println("0");
                }
            } else if (string.equals("top")) { // top또 empty와 유사
                if (top == -1) {
                    System.out.println("-1");
                } else { // 다만 정수가 들어있을시 최상단의 정보를 보여주어야하니 배열의 top번째에 있는 수를 호출
                    System.out.println(arr[top]);
                }
            }

        }
        scanner.close();
    }
}

else if 문을 반복 사용하여 시간초과가 되었다

이를 해결하기 위해 else if 문을 switch 문으로 변환 해보려고 한다.

 

package com.example;

import java.util.Scanner;

public class training {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int a = scanner.nextInt(); // 명령의 수

        int[] arr = new int[a]; // 명령의 수만큼의 크기 배열 선언
        int top = -1; // 최상단 정보

        for (int i = 0; i < a; i++) {
            String string = scanner.next();
            switch (string) {
                case "push":
                    top++;
                    arr[top] = scanner.nextInt();
                    break;

                case "pop":
                    if (top == -1) {
                        System.out.println("-1");
                    } else {
                        System.out.println(arr[top]);
                        top--;
                    }
                    break;

                case "size":
                    System.out.println(top + 1);
                    break;

                case "empty":
                    if (top == -1) {
                        System.out.println("1");
                    } else {
                        System.out.println("0");
                    }
                    break;

                case "top":
                    if (top == -1) {
                        System.out.println("-1");
                    } else {
                        System.out.println(arr[top]);
                    }
                    break;
            }

        }
        scanner.close();
    }
}

채점결과 코드길이는 짧아졌으나 그대로 시간 초과가 떴다.

이는 아마도 Scanner의 기능 이 시간을 오래잡아 먹는거라고 판단된다.

그래서 이번에는 Scanner를 BufferedReader로 수정하여 시간을 줄여보고자한다

 

package com.example;

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

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

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

        int a = Integer.parseInt(br.readLine()); // 명령의 수
        int[] arr = new int[a]; // 명령의 수만큼의 크기 배열 선언
        int top = -1; // 최상단 정보

        for (int i = 0; i < a; i++) {
            String[] string = br.readLine().split(" "); // string을 스플릿으로 공백을 기준으로 나누었다
            switch (string[0]) {					//결과로 string[0] 과 string[1]이 생성되었고
                case "push":						// 0은 push와같은 문자열을 1은 추가될 숫자를 받아왔다
                    top++;
                    arr[top] = Integer.parseInt(string[1]);		//string[1]은 push a 와같은 형식에서 a를 가져온다
                    break;

                case "pop":
                    if (top == -1) {
                        System.out.println("-1");
                        break;
                    } else {
                        System.out.println(arr[top]);
                        top--;
                        break;
                    }

                case "size":
                    System.out.println(top + 1);
                    break;

                case "empty":
                    if (top == -1) {
                        System.out.println("1");
                    } else {
                        System.out.println("0");

                    }
                    break;
                case "top":
                    if (top == -1) {
                        System.out.println("-1");

                    } else {
                        System.out.println(arr[top]);

                    }
                    break;
            }

        }

    }
}

 

결과는 통과

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

6. 9012번 괄호 ( java )  (0) 2021.09.02
5. 9093번 단어 뒤집기 ( java )  (0) 2021.09.02
3. 2884번 알람시계 ( java )  (0) 2021.08.30
2. 2753번 윤년 ( java )  (0) 2021.08.30
1. 14681번 사분면 고르기 ( java )  (0) 2021.08.30