[boj] (s4) 9012 괄호

강신현·2022년 4월 2일
0

✅ stack

문제

링크

풀이

'('가 나오면 stack에 추가하고 ')'가 나오면 stack에서 '(' 하나를 빼낸다. 이때 stack이 비어있으면 NO이다.
또한 작업을 완료한 뒤 stack에 남아있는게 있으면 NO

코드

#include <iostream>
#include <algorithm>
#include <string>
#include <stack>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int T;
    cin >> T;
    while(T--){
        stack<char> st;
        string str;
        bool ans = true;
        cin >> str;

        for (int i = 0; i < str.length(); i++)
        {
            if (str[i] == '(')
                st.push('(');
            else
            {
                if (st.empty())
                {
                    ans = false;
                    break;
                }
                else
                {
                    st.pop();
                }
            }
        }
        if (!st.empty())
            ans = false;

        if (ans == true)
            cout << "YES"
                 << "\n";
        else
            cout << "NO"
                 << "\n";
    }
    return 0;
}
profile
땅콩의 모험 (server)

0개의 댓글