공부기록/Study

5-1 올바른 괄호

메델 2023. 9. 14. 03:05
import java.util.Scanner;
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        String s = kb.next();
        String answer = "YES";
        Stack<Character> stack = new Stack<>();

        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    answer = "NO";
                    break; 
                }
                stack.pop();
            }
        }

        if (!stack.isEmpty()) {
            answer = "NO";
        } 

        System.out.print(answer);
    }
}