[문제 링크]

 

algospot.com :: BRACKETS2

Mismatched Brackets 문제 정보 문제 Best White is a mathematics graduate student at T1 University. Recently, he finished writing a paper and he decided to polish it. As he started to read it from the beginning, he realized that some of the formulas ha

www.algospot.com


스택을 이용하여 풀 수 있는 간단한 문제였다.

 

여는 괄호는 바로 스택에 쌓고, 닫는 괄호의 경우 스택의 top()에 해당 괄호를 여는 괄호가 있는지 확인하여 있다면 여는 괄호를 스택에서 pop() 해주고, 없다면 잘못된 괄호이므로 "NO"를 반환해준다.

 

마지막으로 입력받은 괄호 문자열의 끝까지 탐색했다면 스택이 비어있는지 확인 후 비었을 경우 "YES", 비어있지 않을 경우 "NO"를 반환하도록 구현하였다.


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

string Solution(string str)
{
	stack<char> stk;
	for (int i = 0; i < str.size(); i++)
	{
		switch (str[i])
		{
		case ')':
			if (stk.empty() || stk.top() != '(')
				return "NO";
			stk.pop();
			break;

		case '}':
			if (stk.empty() || stk.top() != '{')
				return "NO";
			stk.pop();
			break;

		case ']':
			if (stk.empty() || stk.top() != '[')
				return "NO";
			stk.pop();
			break;

		default:
			stk.push(str[i]);
		}
	}

	return stk.empty() ? "YES" : "NO";
}

int main(void)
{
	int tc;
	cin >> tc;

	while (tc--)
	{
		string str;
		cin >> str;

		cout << Solution(str) << endl;
	}

	return 0;
}

알고리즘 200일 프로젝트 - 136 day

+ Recent posts