백준 9012 - 괄호

황재진·2024년 3월 5일

백준

목록 보기
13/54
post-thumbnail

괄호 '('와 ')'의 개수가 동일해야 하고, 무조건 '('가 먼저 와야하는 것을 봤을 때 스택을 이용해 해결할 수 있습니다.

'('가 오면 스택을 쌓고 ')'가 오면 빼면 됩니다.

#include<iostream>

int main()
{
	int t;
	std::cin >> t;

	std::string str;
	int stack[51];

	for (int i = 0; i < t; i++)
	{
		std::cin >> str;
		bool result = true;

		int len = str.size();

		std::fill_n(stack, 51, -1);

		int cur_top = -1;

		for (int j = 0; j < len; j++)
		{
			if (str[j] == '(')
				str[++cur_top] = 1;
			else
			{
				if (cur_top == -1)
				{
					result = false;
					break;
				}
				str[cur_top--] = -1;
			}
		}

		if (cur_top == -1 && result)
			std::cout << "YES\n";
		else
			std::cout << "NO\n";
	}

	return 0;
}
profile
프로그래밍, 쉐이더 등 이것저것 다해보는 게임 개발자입니다

0개의 댓글