

ArrayList를 사용해서 풀어봤는데 뭔가..... 비효율적인 것 같아서 다른 방식으로도 풀어봤다.
코드의 길이는 큰 차이가 없지만 실행 시간에서 두 배나 차이가 나더라 하하하
import java.io.*; import java.util.*; public class Main { static ArrayList<Integer> stack = new ArrayList<Integer>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); for(int i=0;i<N;i++) { st = new StringTokenizer(br.readLine(), " "); if(st.countTokens()==2) { st.nextToken(); push(Integer.parseInt(st.nextToken())); } else { String command = st.nextToken(); if(command.equals("pop")) pop(); else if(command.equals("size")) size(); else if(command.equals("empty")) empty(); else if(command.equals("top")) top(); } } } static void push(int x) { stack.add(x); return; } static void pop() { if(stack.isEmpty()) { System.out.println(-1); return; } System.out.println(stack.get(stack.size()-1)); stack.remove(stack.size()-1); return; } static void size() { System.out.println(stack.size()); return; } static void empty() { if(stack.isEmpty()) { System.out.println(1); return; } System.out.println(0); return; } static void top() { if(stack.isEmpty()) { System.out.println(-1); return; } System.out.println(stack.get(stack.size()-1)); return; } }
import java.io.*; import java.util.*; public class Main { static int[] stack; // 스택의 사이즈를 0으로 초기화 static int size = 0; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); // 명령어의 개수만큼 배열을 만들어둠 stack = new int[N]; StringBuilder sb = new StringBuilder(); for(int i=0;i<N;i++) { st = new StringTokenizer(br.readLine(), " "); // 입력되는 명령어에 따라 다른 문장을 실행하는 스위치문 switch(st.nextToken()) { case "push": push(Integer.parseInt(st.nextToken())); 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); } static void push(int x) { stack[size] = x; size++; return; } static int pop() { if(size==0) { return -1; } int tmp = stack[size-1]; stack[size-1] = 0; size--; return tmp; } static int size() { return size; } static int empty() { if(size==0) { return 1; } return 0; } static int top() { if(size==0) { return -1; } return stack[size-1]; } }
'Algorithm > [BOJ] - JAVA' 카테고리의 다른 글
[백준] 10845 : 큐 JAVA 풀이 (0) | 2022.09.19 |
---|---|
[백준] 9012 : 괄호 JAVA 풀이 (0) | 2022.09.19 |
[백준] 11444 : 피보나치 수 5 JAVA 풀이 (0) | 2022.09.18 |
[백준] 1629 : 곱셈 JAVA 풀이 (1) | 2022.09.17 |
[백준] 10830 : 행렬 제곱 JAVA 풀이 (0) | 2022.09.16 |