본문 바로가기

알고리즘(C++)/백준 알고리즘

[백준] C++ 9012번 : 괄호

풀이과정


입력받은 문자열의 각 문자를 검사해서 '('일 때 push 하고, ')'일 때 스택의 맨 위의 값이 ')'일 때 pop 한다.

모든 문자 입력 후 스택이 비어있으면 YES를 비어잇지 않다면 NO를 출력한다.

 

 

코드


#include <iostream>
#include <vector>
#include <stack>
#include <string>

using namespace std;

int main()
{
	int iSize = 0;

	cin >> iSize;

	for (int i = 0; i < iSize; ++i)
	{
		stack<char> st;
		string s;
		cin >> s;

		for (int j = 0; j < s.length(); ++j)
		{
			if (st.empty() || s[j] == '(') st.push(s[j]);
			else if (st.top() == '(') st.pop();
		}

		if (st.empty()) cout << "YES" << endl;
		else cout << "NO" << endl;
	}
    
	return 0;
}