본문 바로가기

Problem/ETC

[백준알고리즘] 9012번 괄호

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





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
#include<stack>
#include<string>
using namespace std;
 
int main(void)
{
    int T;
    cin >> T;
    string str;
 
    while (T--)
    {
        stack<char> st;
        cin >> str;
 
        for (int i = 0; i < str.length(); i++)
        {
            // 왼쪽 괄호일 때 넣는다.
            if (str[i] == '(')
            {
                st.push(str[i]);
            }
            // 비어있을 때 빼는 경우 오류가 남. 처리 중요
            else if (str[i] == ')' && !st.empty() && st.top() == '(')
            {
                st.pop();
            }
            else
            {
                st.push(str[i]);
            }
        }
 
        if (st.empty()) cout << "YES" << '\n';
        else  cout << "NO" << '\n';
    }
    return 0;
}
cs