Little Jay

[C++] 백준 9012번 괄호 본문

알고리즘/BOJ

[C++] 백준 9012번 괄호

Jay, Lee 2021. 7. 16. 20:08

stack 자료구조를 배웠으면 풀 수 있는 것 같다.

옛날 자료구조 족보를 보다가 이 문제에 대한

의사코드를 물어보는 문제를 본 적이 있다.

간단하게 ( 가 들어올때만 push 시켜주고

아닐때는 stack에서 pop을 진행해줘서

마지막에 stack에 남아있는 데이터의 여부에 따라

답을 출력하면 되는 문제

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

int main() {
	int testCase;
	cin >> testCase;
	for (int i = 0; i < testCase; i++) {
		stack<char> st;
		string s;
		cin >> s;
		for (int k = 0; k < s.length(); k++) {
			if (st.empty() || s[k] == '(')
				st.push(s[k]);
			else if (st.top() == '(')
				st.pop();
		}
		if (st.empty() == true)
			cout << "YES" << "\n";
		else
			cout << "NO" << "\n";
	}
	return 0;
}

 

Comments