Algorithm/백준

[백준] 9012 괄호 with C++

nowkoes 2023. 5. 10. 00:00

문제설명


입출력 예제


개념

 괄호 검사는 스택을 활용하는 대표적인 문제다. 입력받는 문자가 소괄호이기 때문에 스택에서 하나씩 꺼내어 괄호 문자열이 맞는지 확인하면 된다.


풀이

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

int main()
{
	int N;
	cin >> N;
	string str;

	while (N--)
	{
		stack<char> st;
		cin >> str;

		if (str.size() % 2 == 1)
			cout << "NO\n";

		else
		{
			for (char& ch : str)
			{
				if (st.empty())
					st.push(ch);
                
				else if (ch == '(')
					st.push(ch);

				else if (ch == ')' && st.top() == '(')
					st.pop();
			}

			if (st.empty())
				cout << "YES\n";

			else
				cout << "NO\n";
		}
	}
}

 

반응형

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

[백준] 1874 스택 수열 with C++  (0) 2023.05.12
[백준] 4949 균형잡힌 세상 with C++  (0) 2023.05.11
[백준] 10773 제로 with C++  (0) 2023.05.09
[백준] 10828 스택 with C++  (0) 2023.05.08
[백준] 1010 다리 놓기 with C++  (0) 2023.05.06