https://www.acmicpc.net/problem/10828
입력값 중에서 4개는 하나의 단어로 이루어져있으므로 해당되면 다음 i로 넘어가도록 continue를 해놓고, 남은 한 가지의 경우에는 두 단어 이루어져있으므로 StringTokenizer로 받아서 문제를 풀이하였다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class Baekjoon_10828_스택 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < N; i++) {
String str = br.readLine();
if (str.equals("top")) {
if (stack.isEmpty())
System.out.println(-1);
else
System.out.println(stack.peek());
continue;
}
if (str.equals("size")) {
System.out.println(stack.size());
continue;
}
if (str.equals("empty")) {
if (!stack.isEmpty())
System.out.println(0);
else
System.out.println(1);
continue;
}
if (str.equals("pop")) {
if (stack.isEmpty())
System.out.println(-1);
else
System.out.println(stack.pop());
continue;
}
StringTokenizer st = new StringTokenizer(str);
str = st.nextToken();
if (str.equals("push")) {
stack.push(Integer.parseInt(st.nextToken()));
}
}
br.close();
}
}
'알고리즘' 카테고리의 다른 글
[백준/Java] 2042 : 구간 합 구하기 (2) | 2025.02.17 |
---|---|
[백준/Java] 1012 : 유기농 배추(BFS) (0) | 2025.02.16 |
[백준/Java] 4963 : 섬의 개수(BFS) (0) | 2025.02.16 |
[백준/Java] 2667 : 단지번호붙이기(BFS) (0) | 2025.02.16 |
[백준/Java] 9012 : 괄호 (0) | 2025.02.16 |