[백준/JAVA] 10828번: 스택
🔺 문제
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
🔺 코드
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Stack<Integer> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
for(int i = 0 ; i < n ; i++) {
String[] input = br.readLine().split(" ");
if(input[0].equals("push")) {
stack.push(Integer.parseInt(input[1]));
}
else if(input[0].equals("top")) {
if(stack.isEmpty()) {
list.add(-1);
} else {
list.add(stack.peek());
}
}
else if(input[0].equals("size")) {
list.add(stack.size());
}
else if(input[0].equals("empty")) {
if(stack.isEmpty()) {
list.add(1);
} else {
list.add(0);
}
}
else if(input[0].equals("pop")) {
if(stack.isEmpty()) {
list.add(-1);
} else {
list.add(stack.pop());
}
}
}
for(int i : list) {
System.out.println(i);
}
}
}
✅ 해결 아이디어
- 스택
💥 유의사항
⇨ 1) 입력이 top, size, empty, pop
처럼 문자열 하나인 경우와
2) 입력이 push 1
처럼 되는 경우가 있는데
이를 위해 매 줄을 입력받을 때 .split(" ")
을 해줘서 String 배열로 만들었다.
String[] input = br.readLine().split(" ");
그러고 나면 input[0]
이 top, size, empty, pop으로,
push 뒤에 들어갈 숫자는 input[1]
으로 입력받을 수 있다.
🔺 다른 풀이들
[JAVA] 백준 10828번 - 스택
📖 문제 📋 코드 import java.util.*; public class Main { public static Stack stack = new Stack(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuffer sb = new StringBuffer(); int N = sc.nextInt(); for (int i =
cocoon1787.tistory.com
[백준] 10828번 스택 - Java, 자바
https://www.acmicpc.net/problem/10828스택에 관한 정석적인 문제 위와 같이 쓸 줄 알면 된다.
velog.io
다덜 switch - case문을 사용하셨다.
💬 느낀 점
나도 다음엔 멋지게 switch - case문을 써야지.