백준 10828번(java)

Wook _·2022년 3월 29일
0

알고리즘-문제

목록 보기
3/11

백준 10828번 문제는 스택이다.
문제는 다음과 같다.
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 다섯 가지이다.

push X: 정수 X를 스택에 넣는 연산이다.
pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
size: 스택에 들어있는 정수의 개수를 출력한다.
empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.

처음 문제는 간단하게 배열을 사용하여 해결하려 하였지만 Index에러를 해결하지 못해 결국 ArrayList를 사용하여 편하게 해결하였다.
문제의 해결은 다음과 같이 생각했다.

push x
StringTokenizer로 String을 받아 nextElement()가 "push"일 경우 다시 nextElement()을 실행하여 x값 입력.

pop
nextElement()가 "pop"일 경우 ArrayList.get(ArrayList.size()-1) 하여 값 출력
ArrayList.size() == 0 일 경우 -1 출력.

size
nextElement()가 "size"일 경우 ArrayList.size() 출력

empty
nextElement()가 "empty"인 경우 ArrayList.isEmpty()의 결과에 따라 false라면 0, true라면 1 출력.

그리하여 코드는 다음과 같다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		ArrayList<Integer> arr = new ArrayList<Integer>();
		
		int cnt = Integer.parseInt(br.readLine());
		
		for(int i = 0; i < cnt; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			String str = st.nextToken();
			int num = 0;
			if(str.equals("push")) {
				arr.add(Integer.parseInt(st.nextToken()));
			}
			else if(str.equals("pop")) {
				if(arr.isEmpty()) System.out.println(-1);
				else {
					num = arr.get(arr.size()-1);
					System.out.println(num);
					arr.remove(arr.size()-1);
				}
			}
			else if(str.equals("size")) {
				System.out.println(arr.size());
			}
			else if(str.equals("empty")) {
				if(arr.isEmpty()) System.out.println(1);
				else System.out.println(0);
			}
			else if(str.equals("top")) {
				if(arr.isEmpty()) System.out.println(-1);
				else
					System.out.println(arr.get(arr.size()-1));
			}
		}
	}
}
profile
책상 위에 있는 춘식이 피규어가 귀엽다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN