백준/C++
백준 9012번 : 괄호 [C++]
대니스
2022. 8. 15. 12:07
주소 : https://www.acmicpc.net/problem/9012
9012번: 괄호
괄호 문자열(Parenthesis String, PS)은 두 개의 괄호 기호인 ‘(’ 와 ‘)’ 만으로 구성되어 있는 문자열이다. 그 중에서 괄호의 모양이 바르게 구성된 문자열을 올바른 괄호 문자열(Valid PS, VPS)이라고
www.acmicpc.net
소스 코드 :
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stack>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
int n = 0;
cin >> n;
for(int i=0;i<n;i++)
{
stack<string> stack;
string str;
cin >> str;
int size = str.length();
int num = 0;
for (int i = 0;i < size;i++)
{
if (str[i] == '(')
{
string element = "(";
stack.push(element);
num++;
}
else if (str[i] == '[')
{
string element = "[";
stack.push(element);
num++;
}
else if (str[i] == ')')
{
if (stack.size() != 0)
{
string check = stack.top();
if (check == "(")
stack.pop();
}
num--;
}
else if (str[i] == ']')
{
if (stack.size() != 0)
{
string check = stack.top();
if (check == "[")
stack.pop();
}
num--;
}
}
if (stack.empty() && num == 0)
cout << "YES" << '\n';
else
cout << "NO" << '\n';
while (!stack.empty())
stack.pop();
}
}
마무리 : 이 문제는 4949번 '균형잡힌 세상' 과 유사한 문제로 스택을 이용하면서 '('가 나오면 스택에 push하고 ')'이 나오면 pop을 하는 식으로 소스 코드를 짜면 된다.