[Algorithm/C++] 2752번 :: 괄호

Sujung Shin·2022년 11월 8일

BOJ 2752번 :: 괄호
굳이 C++의 STL에 정의된 stack을 쓰지 않고도 구현할 수 있다.
단순히 "YES"값과 "NO" 값만 리턴하면 되기 때문이다.

답안 소스코드:

#include <iostream>
#include <string>

using namespace std;

string valid(string s) {
  int cnt = 0; //stack의 사이즈
  for(int i = 0; i < s.size(); i++) {
    if(s[i] == ')') {
      cnt--;
    } else {
      cnt++;
    }
    if(cnt < 0) return "NO";
  }
  if(cnt == 0) return "YES";
  else return "NO";
}

int main() {
  int t;
  cin >> t;
  while(t--) {
    string s;
    cin >> s;
    cout << valid(s) << '\n';
  }
  return 0;
}
profile
백문이불여일타

0개의 댓글