<Java>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import java.util.Scanner; public class Main { public static void main(String[] args) { run(); } public static void run() { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int[] stack = new int[t]; int top = -1; String command; sc.nextLine(); //입력 버퍼에 남은 개행 처리 for(int i = 0; i < t; ++i) { command = sc.nextLine(); if(command.equals("size")) { System.out.println(top + 1); } else if(command.equals("empty")) { System.out.println((top == -1) ? 1 : 0); } else if(command.equals("top")) { System.out.println((top == -1) ? -1 : stack[top]); } else if(command.equals("pop")) { System.out.println((top == -1) ? -1 : stack[top--]); } else if(command.matches("push [0-9]*")) { stack[++top] = Integer.parseInt(command.substring(5)); } } } } | cs |
String 클래스의 matches 메소드는 자신의 문자열이 매개변수로 주어진 정규표현식에 맞는지 검사한다. 34행의 정규표현식에서 [0-9] 는 0부터 9까지의 숫자를, + 는 1글자 이상을 의미한다.
Integer 클래스의 정적 메소드 parseInt() 는 매개변수로 주어진 문자열을 정수로 변환한다. 변환할 수 없을 경우 NumberFormatException 예외를 발생시킨다.
또한 Scanner 클래스의 nextXXX 메소드 중 nextLine 메소드를 제외한 나머지는 입력 버퍼에 개행을 남기기 때문에 18행과 같이 개행을 정리하지 않으면 command 에는 아무것도 입력되지 않는다.
'Programming > Solutions' 카테고리의 다른 글
[BAEKJOON] 2747번 (0) | 2019.06.18 |
---|---|
[BAEKJOON] 15552번 (0) | 2019.06.17 |
[Project Euler] Problem 024 (0) | 2019.05.19 |
[BAEKJOON] 9020번 (0) | 2019.05.17 |
[BAEKJOON] 4948번 (0) | 2019.05.17 |