[백준] 9012번: 괄호

짜장범벅·2022년 7월 24일
0

백준

목록 보기
2/26

1. 문제

괄호의 string을 입력받아 괄호 쌍이 맞는 경우와 아닌 경우를 확인

2. 구현

2.1 Idea

'('이 들어온 경우 stack에 push, ')'이 들어온 경우 pop을 한 다음, 마지막에 stack이 비어있다면 true, 아닌 경우 false

2.2 Code

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

#include <iostream>
#include <vector>
#include <stack>

bool CheckVps(const std::string& str){
    std::stack<int> s;

    for (const auto& c : str){
        if (c == '('){
            s.push(1);
        }
        else if (c == ')'){
            if (s.empty()){
                //'(' 이 부족한데 ')'가 나온 경우
                return false;
            }
            else{
                s.pop();
            }
        }
    }

    bool isVps = false;
    if (s.empty()){
        isVps = true;
    }
    else{
        isVps = false;
    }

    return isVps;
}

int main(){
    int n = 0;
    std::cin >> n;

    std::vector<std::string> v;
    for (int i=0; i<n; ++i){
        std::string input;
        std::cin >> input;

        v.push_back(input);
    }

    for (const auto& str : v){
        if (CheckVps(str)){
            std::cout << "YES" << std::endl;
        }
        else{
            std::cout << "NO" << std::endl;
        }
    }

    return 0;
}
profile
큰일날 사람

0개의 댓글