[백준] 10828번: 스택

앙이🐯·2022년 1월 7일
0

알고리즘

목록 보기
10/22

백준 10828번: 스택

1. 문제 설명

  • 예제 입력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

2. 문제 풀이

  • 명령 N 이 최대 10,000이고 명령마다 매번 println으로 출력 시 시간 초과가 발생할 수 있으므로 StringBuilder를 사용하여 출력
  • StringBuilder: append()를 사용하여 String과 문자열을 더할 때 새로운 객체를 생성하는 것이 아니라 기존 데이터에 더하는 방식이라 속도가 빠름
StringBuffer sb = new StringBuffer();
sb.append(-1+"\n");
코드1 (System.out.Println 사용)
import java.util.*;

public class No_10828 {

	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		
		Stack <Integer> stack=new Stack<Integer>();
		
		int cnt=sc.nextInt();
		
		for(int i=0;i<cnt;i++) {
			String str=sc.next();
			
			if(str.contains("push")) {
				int num=sc.nextInt();
				stack.push(num);
			}else if(str.equals("pop")) {
				if(!stack.isEmpty()) {
					System.out.println(stack.pop());
				}
				else {
					System.out.println(-1);
				}
			}
			else if(str.equals("size")) {
				System.out.println(stack.size());
			}
			else if(str.equals("empty")) {
				if(!stack.isEmpty()) {
					System.out.println(0);
				}
				else
					System.out.println(1);
			}
			else if(str.equals("top")) {
				if(!stack.isEmpty())
					System.out.println(stack.peek());
				else 
					System.out.println(-1);
			}
		}
		
	}

}
코드 1: 실행 결과
  • 시간초과 발생!

코드2 (StringBuilder 사용)
import java.util.*;

public class No_10828 {

	public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		StringBuffer sb = new StringBuffer();
		
		Stack <Integer> stack=new Stack<Integer>();
		
		int cnt=sc.nextInt();
		
		for(int i=0;i<cnt;i++) {
			String str=sc.next();
			
			if(str.contains("push")) {
				int num=sc.nextInt();
				stack.push(num);
			}else if(str.equals("pop")) {
				if(!stack.isEmpty()) {
					sb.append(stack.pop()+"\n");
				}
				else {
					sb.append(-1+"\n");
				}
			}
			else if(str.equals("size")) {
				sb.append(stack.size()+"\n");
			}
			else if(str.equals("empty")) {
				if(!stack.isEmpty()) {
					sb.append(0+"\n");
				}
				else
					sb.append(1+"\n");
			}
			else if(str.equals("top")) {
				if(!stack.isEmpty())
					sb.append(stack.peek()+"\n");
				else 
					sb.append(-1+"\n");
			}
		}
		System.out.println(sb);
	}

}
코드 2: 실행 결과

0개의 댓글