ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [BOJ-JAVA] 10828번: 스택
    Algorithm/Baekjoon Online Judge 2023. 4. 6. 14:21

    문제풀이

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

     

    10828번: 스택

    첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

    www.acmicpc.net

    스택 개념만 알고있다면 문제 자체는 어렵지 않지만 초기 작성한 코드와 이를 개선시키면서 어떻게 작성해야 효율적인지 고민했다.

     

    초기 Java 코드

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    class Stack{
        ArrayList<Integer> list;
        int point;
        public Stack(){
            this.list = new ArrayList<Integer>();
            this.point = 0;
        }
    
        public void push(int num){
            this.list.add(num);
            this.point++;
        }
    
        public int pop(){
            if(point == 0){
                return -1;
            }
            this.point--;
            return this.list.remove(point);
        }
    
        public int size(){
            return this.point;
        }
    
        public int empty() {
            return point > 0 ? 0 : 1;
        }
    
        public int top() {
            if(point == 0) {
                return -1;
            }
            return list.get(point-1);
        }
    }
    
    public class Main{
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            int num = Integer.valueOf(bufferedReader.readLine());
            Stack stack = new Stack();
            for(int i=0; i < num; i++){
                String[] orders = bufferedReader.readLine().split(" ");
                String order = orders[0];
                switch (order) {
                    case "push":
                        stack.push(Integer.valueOf(orders[1]));
                        break;
                    case "pop":
                        System.out.println(stack.pop());
                        break;
                    case "size":
                        System.out.println(stack.size());
                        break;
                    case "empty":
                        System.out.println(stack.empty());
                        break;
                    case "top":
                        System.out.println(stack.top());
                        break;
                    default:
                        break;
                }
            }
        }
    }

    2nd Java 코드

    • 초기 코드에서 클래스 분리 안함
    • static 변수와 함수로 구현
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    
    public class Main{
        public static ArrayList<Integer> list = new ArrayList<Integer>();
        public static int point= 0;
    
        public static void push(int num){
            list.add(num);
            point++;
        }
    
        public static int pop(){
            if(point == 0){
                return -1;
            }
            point--;
            return list.remove(point);
        }
    
        public static int size(){
            return point;
        }
    
        public static int empty() {
            return point > 0 ? 0 : 1;
        }
    
        public static int top() {
            if(point == 0) {
                return -1;
            }
            return list.get(point-1);
        }
        
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            int num = Integer.valueOf(bufferedReader.readLine());
        
            for(int i=0; i < num; i++){
                String[] orders = bufferedReader.readLine().split(" ");
                String order = orders[0];
                switch (order) {
                    case "push":
                        push(Integer.valueOf(orders[1]));
                        break;
                    case "pop":
                        System.out.println(pop());
                        break;
                    case "size":
                        System.out.println(size());
                        break;
                    case "empty":
                        System.out.println(empty());
                        break;
                    case "top":
                        System.out.println(top());
                        break;
                }
            }
        }
    }

    3nd Java 코드

    • 2nd 코드에서 System.out.println()의 횟수를 줄임
    • StringBuilder를 사용하여 마지막에 출력
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    
    public class Main{
        public static ArrayList<Integer> list = new ArrayList<Integer>();
        public static int point= 0;
    
        public static void push(int num){
            list.add(num);
            point++;
        }
    
        public static int pop(){
            if(point == 0){
                return -1;
            }
            point--;
            return list.remove(point);
        }
    
        public static int size(){
            return point;
        }
    
        public static int empty() {
            return point > 0 ? 0 : 1;
        }
    
        public static int top() {
            if(point == 0) {
                return -1;
            }
            return list.get(point-1);
        }
        
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            StringBuilder sb = new StringBuilder();
            int num = Integer.valueOf(bufferedReader.readLine());
            
            for(int i=0; i < num; i++){
                String[] orders = bufferedReader.readLine().split(" ");
                String order = orders[0];
                switch (order) {
                    case "push":
                        push(Integer.valueOf(orders[1]));
                        break;
                    case "pop":
                        sb.append(pop()).append('\n');
                        break;
                    case "size":
                        sb.append(size()).append('\n');
                        break;
                    case "empty":
                        sb.append(empty()).append('\n');
                        break;
                    case "top":
                        sb.append(top()).append('\n');
                        break;
                }
            }
            System.out.println(sb);
        }
    }

     

    결론

    초기 코드
    2nd 코드
    3nd 코드

    • static 변수, 함수로 할경우 코드 길이는 줄지만 메모리가 증가 -> 코드는 잘 알아보는게 중요하기때문에 static 변경이 무조건 좋은 건 아님
    • StringBuilder를 사용했을 경우 시간이 획기적으로 감소
    • 추가적으로 편의를 위해 ArrayList를 사용했지만 ArrayList대신 그냥 배열을 사용했다면 더 시간이 줄것으로 예상됨

    'Algorithm > Baekjoon Online Judge' 카테고리의 다른 글

    [BOJ-JAVA] 1158번: 요세푸스 문제  (0) 2023.04.12
    [BOJ-JAVA] 1406번: 에디터  (0) 2023.04.07
    [BOJ] 10986번: 나머지 합  (0) 2022.04.27
    [BOJ] 12865번: 평범한 배낭  (0) 2022.04.16
    [BOJ] 9251번: LCS  (0) 2022.04.15

    댓글

Designed by Tistory.