[백준] 4949번 균형잡힌 세상 / C++
#문제
#풀이
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
string str;
while (true)
{
getline(cin, str);
stack<char> s;
if (str[0] == '.')
{
break;
}
for (int i = 0; i < str.length() - 1; ++i)
{
if (str[i] == '(')
{
s.push('(');
}
else if (str[i] == '[')
{
s.push('[');
}
else if (str[i] == ')')
{
if (!s.empty() && s.top() == '(')
{
s.pop();
}
else
{
cout << "no" << '\n';
break;
}
}
else if (str[i] == ']')
{
if (!s.empty() && s.top() == '[')
{
s.pop();
}
else
{
cout << "no" << '\n';
break;
}
}
if (s.empty() && i == str.length() - 2)
{
cout << "yes" << '\n';
}
else if (!s.empty() && i == str.length() - 2)
{
cout << "no" << '\n';
}
}
}
}
#정리
스택 자료구조를 사용하여 해결할 수 있는 간단한 문제. 주어진 문자가 '(', '[' 일 경우 스택에 넣고, ')', ']' 경우에는 스택의 top에 짝이 있는지 확인하는데, 있을 경우 pop, 없을 경우 “no”를 출력하고 문자열을 끝낸다. '.'이 나올 때까지 문자열이 empty가 된다면 “yes”, 안 된다면 “no”를 출력한다.
Enjoy Reading This Article?
Here are some more articles you might like to read next: