[백준] 10828

ninano05·2026년 3월 17일
import java.util.*;
import java.io.*;

public class Main{
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int n = Integer.parseInt(br.readLine());
        String[] command = new String[n]; // 명령어 담아두기
        int[] s = new int[n]; // 명령 숫자 담기
        
        for(int i=0; i<n; i++) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            String comm = st.nextToken();
            // 문자만 들어오는 경우도 있음
            if(comm.equals("push")) {
                command[i] = comm;
                s[i] = Integer.parseInt(st.nextToken());
            } else {
                command[i] = comm;
                s[i] = -1;
            }
        }
        
        for(int r : solution(n, command, s)) {
            bw.write(r+"\n");
        }
        
        bw.flush();
        bw.close();
        br.close();
    }
    
    public static ArrayList<Integer> solution(int n, String[] command, int[] s) {
        Stack<Integer> stack = new Stack<>();
        ArrayList<Integer> answer = new ArrayList<>();
        int index = 0; // 출력 저장 인덱스
        
        for(int i=0;i<n;i++) {
            if(command[i].equals("push")) {
                stack.push(s[i]);
            } else if(command[i].equals("pop")) {
                if(stack.isEmpty()) { //스택이 비어있는 경우
                    answer.add(-1);
                    index++;
                } else {
                    answer.add(stack.pop());
                    index++;
                }     
            } else if (command[i].equals("size")){
                answer.add(stack.size());
                index++;
            } else if (command[i].equals("empty")) {
                if(stack.isEmpty()) {
                    answer.add(1);
                    index++;
                } else {
                    answer.add(0);
                    index++;
                }
            } else if (command[i].equals("top")) {
                if(stack.isEmpty()) { //스택이 비어있는 경우
                    answer.add(-1);
                    index++;
                } else {
                    answer.add(stack.peek());
                    index++;
                }  
            }
        }
        return answer;
    }
}
  • 문자열 비교할 때는 == 대신 equals를 사용한다.
    - (==)는 기본형 int, double, char 비교시 사용
    • (==)는 객체의 주소 비교시에도 사용 (*객체인 경우는 무조건 주소 비교니까, 값을 비교하고 싶으면 사용하지 말기)
    • .equals() 객체 string, 배열, 클래스 비교시 사용
  • 배열은 고정이라 한계가 많으니, ArrayList 적극 활용할 것
profile
초보 개발자

0개의 댓글