백준 알고리즘(C++)

백준 9012번 괄호 ( C++ )

coding232624 2024. 3. 23. 23:47

문제

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

 

9012번: 괄호

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

www.acmicpc.net

 

해설

전형적인 스택 문제

함수로 만들어서 구현하면 check함수를 없애며 조금 더 단조롭게 코드를 짤 수 있음

코드

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
#include <bits/stdc++.h>
using namespace std;
int t;
string line;
bool check;
 
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
 
  cin >> t;
  for (int i = 0; i < t; i++)
  {
    cin >> line;
    check = true;
    stack<char> stk;
    for (char c : line)
    {
      if (c == '(')
        stk.push(c);
      else if (stk.empty())
      {
        cout << "NO\n";
        check = false;
        break;
      }
      else
        stk.pop();
    }
    if (check && stk.empty())
      cout << "YES\n";
    else if (check)
      cout << "NO\n";
  }
}
cs