백준 괄호

황상익·2023년 12월 18일
0

백준

목록 보기
8/15
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

public class 괄호 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();

        for (int i = 0; i < T; i++) {
            System.out.println(solution1(sc.next()));
        }
    }

    public static String solution1(String str) {
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);

            if (c == '(') {
                stack.push(c);
            } else if (stack.isEmpty()) {
                return "NO";
            } else {
                stack.pop();
            }
        }
        if (stack.empty()) {
            return "YES";
        } else {
            return "NO";
        }
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class 괄호_1 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int T = Integer.parseInt(br.readLine());

       while (T --> 0){
           sb.append(sovle(br.readLine())).append('\n');
       }
        System.out.println(sb);
    }

    public static String sovle(String s){
      int cnt = 0;

        for (char c:
             s.toCharArray()) {
            if (c == '('){
                cnt++;
            } else if (cnt == 0){
                return "NO";
            } else {
                cnt --;
            }
        }

        if (cnt==0){
            return "YES";
        } else {
            return "NO";
        }
    }
}
profile
개발자를 향해 가는 중입니다~! 항상 겸손

0개의 댓글