본문 바로가기
알고리즘/백준

백준 9012번 - 괄호 (Java 8)

by latissimus 2022. 3. 8.

https://www.acmicpc.net/problem/9012

 

9012번: 괄호

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고

www.acmicpc.net

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class Main {
    static Stack<Character> stack = new Stack<>();

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int numOfCase = Integer.parseInt(br.readLine());

        for (int i = 0; i < numOfCase; i++) {
            String input = br.readLine();
            stack.clear();
            System.out.println(checkVPS(input));
        }
    }

    public static String checkVPS(String input) {
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);

            if (ch == '(') {
                stack.push('(');
            }
            if(stack.isEmpty()){
                return "NO";
            }
            if ((!stack.isEmpty()) && ch == ')' ) {
                stack.pop();
            }
        }
        if (stack.empty()) {
            return "YES";
        }
        return "NO";
    }
}

 

참고 : 

https://st-lab.tistory.com/178

 

[백준] 9012번 : 괄호 - JAVA [자바]

www.acmicpc.net/problem/9012 9012번: 괄호 괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올..

st-lab.tistory.com

 

댓글