알고리즘 공부

백준 9012번 괄호 C++

빵어 2023. 10. 4. 20:00

Stack을 사용하지 않았을 때

#include <iostream>
using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n = 0;
	cin >> n;

	string s = "";
	int countL = 0, countR = 0;
	bool isNO = false;
	for (int i = 0; i < n; ++i) {
		countL = 0;
		countR = 0;
		isNO = false;

		cin >> s;

		for (int j = 0; j < s.size(); ++j) {
			if (s[j] == '(') ++countL;
			else ++countR;

			if (countL < countR)
				isNO = true;
		}

		if (countL == countR && !isNO)
			cout << "YES" << '\n';
		else cout << "NO" << '\n';
	}

	return 0;
}

 

 

Stack을 사용했을 때

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

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n = 0;
	cin >> n;

	stack<char> s;
	string str;
	bool isVPS = true;

	for (int i = 0; i < n; ++i) {
		isVPS = true;
		cin >> str;

		for (char c : str) {
			if (c == '(')
				s.push(c);
			else if (c == ')' && !s.empty())
				s.pop();
			else {
				isVPS = false;
				break;
			}
		}

		if (!s.empty()) {
			isVPS = false;
			while (!s.empty()) s.pop();
		}

		if (isVPS) cout << "YES\n";
		else cout << "NO\n";
	}

	return 0;
}

 

 

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

 

9012번: 괄호

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

www.acmicpc.net