알고리즘/백준-실버

백준 9012번 괄호 (C++) (스택활용)

뜨거운 개발자 2023. 1. 8. 12:14

문제

정답 코드

#include <iostream>
#include <algorithm>
#include <stack>
#include <string>

using namespace std;

int main()
{
	int n;
	cin >> n;
	for (int i=0;i <n;i++)
	{
		int p = 0;
		string s;
		stack <char> st;
		cin >> s;
		for (auto it : s)
		{
			if (it == ')')
			{
				if (st.empty())
				{
					cout <<"NO\n";
					p = 1;
					break;
				}
				st.pop();
			}
			else if (it == '(')
				st.push(it);
		}
		if (p ==1)
			continue;
		else if (!st.empty())
			cout << "NO\n";
		else
			cout << "YES\n";
	}
}

문제 풀이의 흐름

  • 이전에 풀었던 문제인 알고리즘 백준 3986번 좋은단어와 거의 같은 문제이다.
백준 3986번 좋은단어 (C++)(부제 맞왜틀..)
문제정답 코드#include #include #include #include using namespace std; stack a; int check(string s) { if (s.size()%2 != 0) return (0); for (auto it : s) { if (a.empty()) a.push(it); else if (a.top() == it) a.pop(); else a.push(it); } char c1,c2; while (!a.empty()) { c1 = a.top(); a.pop(); if (a.empty()) return (0); c2 = a.top(); a.pop(); if (c1 != c2) { while (!a.empty()) { a.pop(); } return (0); } } r..
https://haward.tistory.com/35

Uploaded by N2T

728x90