본문 바로가기
백준 풀이

[백준 풀이_Java] 9012 괄호 (실버4)

by happyhelen 2023. 11. 13.

 

처음 생각

문제를 딱 보자마자 스택을 써야겠다고 생각했다.

 

 

내가 푼 방법

 

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

public class Main {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int s = Integer.parseInt(br.readLine());
        String strTmp;
        Stack<String> stack;

        for (int i = 0; i < s; i++) {
            strTmp = br.readLine();
            stack = new Stack<>();
            String[] arrTmp = strTmp.split("");

            stack.push(arrTmp[0]);
            for(int j=1; j<arrTmp.length; j++){
                if(")".equals(arrTmp[j]) && !stack.isEmpty() && "(".equals(stack.peek())){
                    stack.pop(); // () 한 쌍 제거
                }else{
                    stack.push(arrTmp[j]);
                }
            }

            if(stack.empty()){
                System.out.println("YES");
            }else{
                System.out.println("NO");
            }

        }

    }

}