[백준] 10829번 : 스택

2021. 3. 24. 22:05백준

접근법

- BufferedReader와 StringBuilder를 이용하여 입력을 받아오려고 생각함.

- 명령어가 push인지 그 외 명령어인지를 구분(어절의 개수로 구분)

- push의 경우 split을 사용하여 두 번째에 해당하는 값을 ArrayList에 저장함.

- 나머지 명령어의 경우 해당 내용에 따라서 코드를 작성

 

 

풀이

package baekjoon;

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

public class Stack_10828 {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
		StringBuilder sb = new StringBuilder();
		
        // ArrayList에 push된 숫자를 저장
		ArrayList<Integer> intlist = new ArrayList<>(); 
		int a = Integer.parseInt(br.readLine());
		
		for (int i = 0; i < a; i++) {
			String s = br.readLine();
			String[] s_arr = s.split(" ");
			
            // 길이가 2어절 이상인 경우(push 명령어의 경우)
			if (s_arr.length > 1) {
				for (int j = 0; j < s_arr.length; j++) {
					if (j != 0) {
						intlist.add(Integer.parseInt(s_arr[j]));
					}
				}				
			}
			else { // push외의 명령어 구분
				if (s.equals("pop")) {
					if (intlist.isEmpty()) {
						System.out.println(-1);
					} else { // 가장 나중에 들어온 인덱스의 값을 출력 후 삭제
						System.out.println(intlist.get(intlist.size() - 1));
						intlist.remove(intlist.size() - 1);
					}
				}else if (s.equals("size")) {
					System.out.println(intlist.size());
				}else if (s.equals("empty")) {
					if (intlist.isEmpty()) {
						System.out.println(1);
					} else {
						System.out.println(0);
					}
				} else {
					if (intlist.isEmpty()) {
						System.out.println(-1);
					} else {
						System.out.println(intlist.get(intlist.size() - 1));
					}
				}
			}
		}
	}
}

 

결과

 

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

[백준] 9461번 : 파도반 수열  (0) 2021.04.21
[백준] 2579번 : 계단 오르기  (0) 2021.04.20
[백준] 1904번 : 01타일  (1) 2021.04.20
[백준] 1003번 : 피보나치 함수  (0) 2021.04.19
[백준] 10819번 : 차이를 최대로  (0) 2021.04.09