백준/기타

9012번: 괄호 [C++]

Koalitsiya 2023. 4. 10. 18:17

문제

 

 

풀이

 문자열을 받아 여는 괄호일 때 cnt를 증가 시키고, 닫는 괄호는 cnt를 감소시킨다. 이후 cnt가 0보다 작다면 flag를 false로 바꾸고 break한다. 반복문이 끝난 후 flag가 false거나 cnt가 0이 아니라면 NO를 출력, 조건을 만족하면 YES를 출력한다.

#include <iostream>
#include <string>

using namespace std;

int main() {
	int n;
	string str;

	cin >> n;

	for (int i = 0; i < n; i++) {
		int cnt = 0;
		bool isVPS = true;

		cin >> str;

		for (int i = 0; i < str.size(); i++) {
			if (str[i] == '(') cnt++;
			else if (str[i] == ')') cnt--;

			if (cnt < 0) {
				isVPS = false;
				break;
			}
		}

		if (isVPS == false || cnt != 0) cout << "NO\n";
		else cout << "YES\n";
	}

	return 0;
}