백준 9012 괄호 ⭕

CJB_ny·2023년 1월 20일
0

백준

목록 보기
59/104
post-thumbnail

괄호

이문제 단순해 보일 수 있는데 예제 입출력 부분에

'())(' 이런 경우 보고 예외 조건이 딱 생각이 났다.

단순히 '(' 나올 때 개수를 세는 식이 아니라

열고, 닫는다. 느낌으로 접근을 함.

문을 열지도 않았는데 닫는다는 건 말이 안되니까.


강의 해설

이런 "짝짓기"같은 문제 나오면은 항상

"stack"을 생각을 해야한다.

'('를 stack에다가 밀어 넣는데 마지막에

return stk.empty()가 있는 이유는 스택에 '('가 남아있으면 NO를 출력해야 하기 때문에.

stack<char > stk;
	for (char c : s)
	{
		if (c == '(') stk.push(c);
		else
		{
			if (!stk.empty()) stk.pop();
			else return false;
		}
	}
	return stk.empty();

cpp 코드

내풀이

#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
#define endl "\n"

int n;
string s;

bool check(string s)
{
	stack<char > stk;
	for (char c : s)
	{
		if (c == '(') stk.push(c);
		else
		{
			if (!stk.empty()) stk.pop();
			else return false;
		}
	}
	return stk.empty();
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> n;
	for (int i = 0; i < n; ++i)
	{
		cin >> s;
		if (check(s)) cout << "YES" << endl;
		else cout << "NO" << endl;
	}

	return 0;
}

stack

#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
#define endl "\n"

int n;
string s;

bool check(string s)
{
	stack<char > stk;
	for (char c : s)
	{
		if (c == '(') stk.push(c);
		else
		{
			if (!stk.empty()) stk.pop();
			else return false;
		}
	}
	return stk.empty();
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> n;
	for (int i = 0; i < n; ++i)
	{
		cin >> s;
		if (check(s)) cout << "YES" << endl;
		else cout << "NO" << endl;
	}

	return 0;
}
profile
https://cjbworld.tistory.com/ <- 이사중

0개의 댓글