10828번

LJM·2022년 12월 30일
0

백준풀기

목록 보기
1/259

스택구현문제이다
시간초과 줄이느라 2시간이 넘게 걸렸다 하...
자바에 익숙하지 않은 부분들 때문에 시간이 오래걸린다 아직은.
그러고 보니 isNumeric 복붙한건 쓰지도 않았네;;

import java.util.Scanner;

public class Main {

    int[] array;
    int     top;

    Main(int n)
    {
        array = new int[n];
        top = -1;
    }

    void push(int n)
    {
        if(top == array.length-1)
        {
            int[] newArray = new int[array.length * 2];
            System.arraycopy(array, 0, newArray, 0, array.length);
            array = null;
            array = newArray;
        }

        top++;
        array[top] = n;
    }

    int pop()
    {
        if(1 == empty())
        {
            return -1;
        }

        int result = array[top];
        top--;

        return result;
    }

    int size()
    {
        return top + 1;
    }

    int empty()
    {
        return (top == -1) ? 1 : 0;
    }

    int top()
    {
        if(1 == empty())
        {
            return -1;
        }
        return array[top];
    }

    public static boolean isNumeric(String s) {
        return s != null && s.matches("[-+]?\\d*\\.?\\d+");
    }

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

        int count = 0;
        count = scan.nextInt();
        Main stack = new Main(count);

        StringBuilder builder = new StringBuilder();

        StringBuilder first = new StringBuilder();
        StringBuilder second = new StringBuilder();
        int idx = 0;
        while(idx < count && scan.hasNext())
        {
            first.setLength(0);
            first.insert(0, scan.next());

            if(first.toString().equals("push"))
            {
                second.setLength(0);
                second.insert(0, scan.next());
                int num = Integer.parseInt(second.toString());

                stack.push(num);
            }
            else if(first.toString().equals("pop"))
            {
                builder.append(stack.pop());
                builder.append("\n");
            }
            else if(first.toString().equals("size"))
            {
                builder.append(stack.size());
                builder.append("\n");
            }
            else if(first.toString().equals("empty"))
            {
                builder.append(stack.empty());
                builder.append("\n");
            }
            else if(first.toString().equals("top"))
            {
                builder.append(stack.top());
                builder.append("\n");
            }

            idx++;
        }

        System.out.println(builder.toString());
        scan.close();

    }
}
profile
게임개발자 백엔드개발자

0개의 댓글