본문 바로가기

개발/알고리즘

백준 9012번 괄호 C++

문제

www.acmicpc.net/problem/9012

 

9012번: 괄호

괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고

www.acmicpc.net

코드

#include<bits/stdc++.h>

using namespace std;
int n;
string str;
vector<string> v;

bool check(string str)
{
    stack<char> s;
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == '(')
        {
            s.push(str[i]);
        }
        else
        {
            if (s.empty() == false)
                s.pop();
            else
            {
                // )인데 (가 없을때
                return false;
            }
        }
    }
    //stack에 괄호 남아있을때
    return s.empty();
}

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

    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> str;
        if (check(str))
            v.push_back("YES");
        else
            v.push_back("NO");
    }

    for (int i = 0; i < n; i++)
    {
        cout << v[i] << "\n";
    }

    return 0;
}

'개발 > 알고리즘' 카테고리의 다른 글

백준 2636번 치즈 C++  (0) 2021.01.16
백준 4949 균형잡힌 세상 C++  (0) 2021.01.15
백준 3473 교수가 된 현우 C++  (0) 2021.01.15
백준 1436 영화감독 숌 C++  (0) 2021.01.14
백준 10709번 기상캐스터 C++  (0) 2021.01.13