반응형
🔺 문제
🔺 코드
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]
으로 입력받을 수 있다.
🔺 다른 풀이들
다덜 switch - case문을 사용하셨다.
💬 느낀 점
나도 다음엔 멋지게 switch - case문을 써야지.
반응형
'코테 > 백준' 카테고리의 다른 글
[백준/JAVA] 2164번: 카드2 (0) | 2023.04.10 |
---|---|
[백준/JAVA] 10773번: 제로 (0) | 2023.04.10 |
[백준/JAVA] 12891번: DNA 비밀번호 (0) | 2023.04.10 |
[백준/JAVA] 11478번: 서로 다른 부분 문자열의 개수 (0) | 2023.04.10 |
[백준/JAVA] 1269번: 대칭 차집합 (0) | 2023.04.10 |