주소 : https://www.acmicpc.net/problem/4949
4949번: 균형잡힌 세상
하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 각 줄은 마침표(".")로 끝난다
www.acmicpc.net
소스 코드 :
#define _SRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
stack<string> stack;
string str;
getline(cin, str);
int size = str.length();
while (1)
{
if (str == ".")
{
break;
}
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();
getline(cin, str);
size = str.length();
}
}
마무리 : 스택을 이용해서 '(', '['이 오면 스택에 push를 했다가 ')', ']' 나올 때 pop을 해서 문장이 끝날 때 균형이 잡힌 문자열이면 'yes'를 출력하고 아니면 'no'를 출력하는 문제이다. 스택을 공부할 때 많이 푸는 문제 중 하나이다.
'백준 > C++' 카테고리의 다른 글
백준 10866번 : 덱 [C++] (0) | 2022.08.18 |
---|---|
백준 9012번 : 괄호 [C++] (0) | 2022.08.15 |
백준 2839번 : 설탕 배달 [C++] (0) | 2022.08.15 |
백준 1920번 : 수 찾기 [C++] (0) | 2022.08.11 |
백준 1018번 : 체스판 다시 칠하기 [C++] (0) | 2022.08.11 |