풀이
- 사실 이문제는 스택 메소드를 사용해보라는거고 중요한건 시간초과를 해결하는거다. 내가 선택한 방법은 System.out.println() 보다 StringBuilder를 통해 문자열을 만들고 한 번의 System.out.println() 통해 출력했다. 스택부터 다시 알고리즘 문제 시작하자 😎
package problem_solving.stack;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
public class BaekJoon_28278 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = Integer.parseInt(sc.next());
Stack<Integer> st = new Stack<>();
StringBuilder sb = new StringBuilder();
while(t -- > 0 ) {
int num = Integer.parseInt(sc.next());
int num2 = 0 ;
if( num == 1 ) {
num2 = Integer.parseInt(sc.next());
}
if(num == 1 ) {
st.push(num2);
} else if(num == 2 ) {
if( !st.isEmpty()) {
sb.append(st.pop()+""+'\n');
}else {
sb.append(-1+""+'\n');
}
} else if(num == 3 ) {
sb.append(st.size()+""+'\n');
} else if(num == 4 ) {
if(!st.isEmpty()) {
sb.append(0+""+'\n');
}else {
sb.append(1+""+'\n');
}
} else if(num == 5 ) {
if( !st.isEmpty()) {
sb.append(st.peek()+""+'\n');
}else {
sb.append(-1+""+'\n');
}
}
}
System.out.println(sb.toString());
}
}