MakerHyeon

[백준] 9012번 괄호 (Python,C++) 본문

Algorithm/backjoon

[백준] 9012번 괄호 (Python,C++)

유쾌한고등어 2023. 1. 27. 00:46

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

 

9012번: 괄호

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

www.acmicpc.net

 

릿코드 문제와 똑같구만...


SOLUTION CODE

# PYTHON

for _ in range(int(input())):
    stk = []
    isVPS = True
    for ch in input():
        if ch == '(':
            stk.append(ch)
        else:
            if stk: # 스택 비어있지않을때
                stk.pop()
            else: # 스택 비어있으면 False
                isVps = False
                break
    
    if stk:
        isVPS = False
        
    print('YES' if isVPS else 'NO')

 

# C++

#include <iostream>
#include <stack>
using namespace std;

string isVPS(string s){
    stack<char> stk;
    for(int i=0; i< s.size();i++){
        if(s[i] == '('){
            stk.push('(');
        }
        else {
            if(s.empty()) return "NO";
            stk.pop();
        }
    }
    string ans = (s.empty())? "YES" : "NO";
    return ans;
}

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

    int input;
    string input_s;
    cin >> input;
    for(int i=0;i<input;i++){
        cin>>input_s;
        cout<< isVPS(input_s)<<'\n';
    }
}
Comments