54. 올바른 괄호 (stack)

zzzzwso·2023년 9월 18일
0

문제설명

괄호가 입력되면 올바른 괄호이면 “YES", 올바르지 않으면 ”NO"를 출력합니다.
(())() 이것은 괄호의 쌍이 올바르게 위치하는 거지만, (()()))은 올바른 괄호가 아니다.

입력설명

첫 번째 줄에 괄호 문자열이 입력됩니다. 문자열의 최대 길이는 30이다.

출력설명

첫 번째 줄에 YES, NO를 출력한다.

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

int main()
{
	string str;
	int flag = 1;
	cin >> str;
	stack<char> s;
	for (int i = 0; i < str.size(); i++)
	{
		if (str[i] == '(')
		{
			s.push('(');
		}
		else
		{
			if (s.empty())
			{
				cout << "NO";
				flag = 0;
				break;
			}
			else
				s.pop();
		}
	}
	if (flag == 1)
	{
		if (s.empty())
			cout << "YES";
		else
			cout << "NO";
	}
	
}
profile
HI there

0개의 댓글