https://www.acmicpc.net/problem/10828
- 예제 입력1
14
push 1
push 2
top
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
top
- 예제 출력1
2
2
0
2
1
-1
0
1
-1
0
3
- 예제 입력2
7
pop
top
push 123
top
pop
top
pop
- 예제 출력2
-1
-1
123
123
-1
-1
- 문제 접근
- 제목 그대로 스택 구현 문제
- 문제 해결
- Stack 클래스와 switch-case문 사용
- 큐 문제처럼 별도로 구현해야하는 명령어는 없음
- 기존 풀이 [메모리 : 21272 KB / 시간 : 220 ms]
public static void main(String[] args) throws Exception{
Stack<Integer> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final int NOT_OUTPUT = -999;
int N = Integer.parseInt(br.readLine());
for(int i = 0; i < N; i++){
String[] command = br.readLine().split(" ");
Integer output = NOT_OUTPUT;
switch(command[0]){
case "push" : stack.push(Integer.parseInt(command[1])); break;
case "pop" : output = stack.empty() ? -1 : stack.pop(); break;
case "size" : output = stack.size(); break;
case "empty" : output = stack.isEmpty() ? 1 : 0; break;
case "top" : output = stack.empty() ? -1 : stack.peek(); break;
}
if(output == null) output = -1;
if(output != NOT_OUTPUT) sb.append(output).append("\n");
}
System.out.println(sb);
}
'Coding Test > Problem Number' 카테고리의 다른 글
[Java] 프린터 큐 [1966번] (0) | 2024.07.24 |
---|---|
[Java] 에디터 [1406번] (0) | 2024.07.24 |
[Java] 큐 [10845번] (0) | 2024.07.24 |
[Java] 3의 배수 [1769번] (0) | 2024.07.24 |
[Java] 단어순서 뒤집기 [12605번] (0) | 2024.07.24 |