문제

 

 

풀이

 문자열을 받아 여는 괄호일 때 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;
}

'백준 > 기타' 카테고리의 다른 글

[백준/C++] 18111번: 마인크래프트  (0) 2023.04.19
[백준/C++] 10773번 : 제로  (0) 2023.04.10
4949번: 균형잡힌 세상 [C++]  (0) 2023.04.10
2164번: 카드2 [C++]  (0) 2023.04.10
1920번: 수 찾기 [C++]  (0) 2023.04.10

+ Recent posts