백준 - 한 줄로 서기 ( 28278번, JAVA )

changi123·2024년 11월 4일
0
post-thumbnail

Stack ( https://www.acmicpc.net/problem/28278 )

풀이

  • 사실 이문제는 스택 메소드를 사용해보라는거고 중요한건 시간초과를 해결하는거다. 내가 선택한 방법은 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());

	}

}

profile
개발자 홍찬기 꾸준한 사람이 되자

0개의 댓글

관련 채용 정보