PS/BOJ

[백준] 9012. 괄호(c++)

backend 개발자 지망생 2025. 2. 16. 20:42

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

올바른 괄호의 쌍을 찾아보았다.

 


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <limits.h>
#include <queue>
#include <set>
#include <math.h>
#include <stack>
#include <deque>

using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int n, ans = 0;

    cin >> n;

    while (n--) {
        string s;
        stack<char> stk;
        bool flag = true;

        cin >> s;

        for (char i : s) {
            if (i == '(') {
                stk.push(i);
            }
            else if(!stk.empty() && i == ')'){
                if (stk.top() == '(')
                    stk.pop();
                else {
                    stk.push(i);
                }
            }
            else {
                flag = false;
                break;
            }
        }

        if (stk.empty() && flag)
            cout << "YES\n";
        else {
            cout << "NO\n";
        }


    }

    return 0;
}