```
백준 4949번 균형 잡힌 세상(balanced world) C++로 구현해보기
```

이번 글을 통해 배워갈 내용
- 백준 4949번 풀이
- 괄호 처리 확인 알고리즘
https://www.acmicpc.net/problem/4949
4949번: 균형잡힌 세상
하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마
www.acmicpc.net
백준 4949번 나는 균형잡힌 세상은
난이도 쉬움 등급의 문제로서
문자열에 소괄호 ( )
와 대괄호 [ ]
가 주어질때
오른쪽 짝과 왼쪽짝이 짝을 잘 이루는지, 1대1 매칭이 되었는지, 문자열이 균형잡혔는지 확인해주는 문제입니다.
30분 정도 위에 링크를 방문하셔서 풀어보시고
안풀리시는 경우에만 아래 해답을 봐주시면 감사하겠습니다.
한줄씩 입력을 받아서 큐에 저장한다음
.이 나오는 경우 입력 종료를 해줍니다.
void getInputFromUser()
{
std::string inputStr;
/* 입력 속도를 줄여서 시간제한을 통과하기 위해서 stringstream 사용*/
while (std::getline(std::cin, inputStr))
{
if (inputStr == ".")
{
break;
}
inputStrQue.push(inputStr);
}
}
한줄씩 큐에서 빼서
확인을 해줍니다.
확인된 값을 출력해줍니다.
void CheckBalanceAndPrint()
{
while (inputStrQue.empty() == false)
{
/* 한줄씩 저장하는 스트링*/
const std::string tempStr = inputStrQue.front();
inputStrQue.pop();
std::cout << bracketBalanceCheck(tempStr) << std::endl;
}
}
괄호가 닫혀있고 정상적으로 짝이 1대1로 매칭되면 yes 아니면 no를 리턴해줍니다.
std::string bracketBalanceCheck(std::string tempStr)
{
/* 스트링을 확인하기 위해 괄호등을 저장하는 스택*/
std::stack<char>stringStack;
for (char ch : tempStr)
{
switch (ch)
{
case '(':
{
stringStack.push('(');
break;
}
case '[':
{
stringStack.push('[');
break;
}
case ')':
{
if (stringStack.empty() ==false && stringStack.top() == '(')
{
stringStack.pop();
}
else
{
return "no";
}
break;
}
case ']':
{
if (stringStack.empty() == false && stringStack.top() == '[')
{
stringStack.pop();
}
else
{
return "no";
}
break;
}
default:
break;
}
}
if (stringStack.empty() == false)
{
return "no";
}
return "yes";
}
전체 코드는 아래와 같습니다.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include<numeric>
// https://www.acmicpc.net/problem/4949
class CBalancedWorld
{
private:
std::queue<std::string> inputStrQue;
public:
CBalancedWorld()
{
}
~CBalancedWorld()
{
}
void getInputFromUser()
{
std::string inputStr;
/* 입력 속도를 줄여서 시간제한을 통과하기 위해서 stringstream 사용*/
while (std::getline(std::cin, inputStr))
{
if (inputStr == ".")
{
break;
}
inputStrQue.push(inputStr);
}
}
void CheckBalanceAndPrint()
{
while (inputStrQue.empty() == false)
{
/* 한줄씩 저장하는 스트링*/
const std::string tempStr = inputStrQue.front();
inputStrQue.pop();
std::cout << bracketBalanceCheck(tempStr) << std::endl;
}
}
std::string bracketBalanceCheck(std::string tempStr)
{
/* 스트링을 확인하기 위해 괄호등을 저장하는 스택*/
std::stack<char>stringStack;
for (char ch : tempStr)
{
switch (ch)
{
case '(':
{
stringStack.push('(');
break;
}
case '[':
{
stringStack.push('[');
break;
}
case ')':
{
if (stringStack.empty() ==false && stringStack.top() == '(')
{
stringStack.pop();
}
else
{
return "no";
}
break;
}
case ']':
{
if (stringStack.empty() == false && stringStack.top() == '[')
{
stringStack.pop();
}
else
{
return "no";
}
break;
}
default:
break;
}
}
if (stringStack.empty() == false)
{
return "no";
}
return "yes";
}
};
int main()
{
CBalancedWorld* cBalancedWorld = new CBalancedWorld();
// 값을 입력받는다.
cBalancedWorld->getInputFromUser();
cBalancedWorld->CheckBalanceAndPrint();
}
입력
()
[]
([][][][])
([][])[[[
([[[[[)
([]()()()[])
.
결과
yes
yes
yes
no
no
yes
읽어주셔서 감사합니다
무엇인가 얻어가셨기를 바라며
오늘도 즐거운 코딩하시길 바랍니다 ~ :)
참조 및 인용
C++ Primer
Introduction to Algorithms
https://codemasterkimc.tistory.com/35
C++ 이론을 배울수 있는 곳 정리
개요 C++을 배우는 책, 강의, 블로그, 링크 등을 공유합니다. (링크 및 간략한 설명을 하였으나 만약 원작자가 링크를 거는것을 원치 않을 경우 연락주시기 바랍니다.) 서적 https://www.amazon.com/Prime
codemasterkimc.tistory.com
https://codemasterkimc.tistory.com/50
300년차 개발자의 좋은 코드 5계명 (Clean Code)
이번 글을 통해 배워갈 내용 좋은 코드(Clean Code)를 작성하기 위해 개발자로서 생각해볼 5가지 요소를 알아보겠습니다. 개요 좋은 코드란 무엇일까요? 저는 자원이 한정적인 컴퓨터 세상에서 좋
codemasterkimc.tistory.com
'C++ > C++ 알고리즘' 카테고리의 다른 글
| 백준1764번 듣보잡 C++로 구현해보기 (0) | 2021.08.29 |
|---|---|
| 백준17219번 비밀번호 찾기 C++로 구현해보기 (0) | 2021.08.29 |
| 백준2609번 GCD, LCM 최대공약수, 최소공배수 C++로 구현해보기 (0) | 2021.08.29 |
| 백준10773번 간단한 스택구조 C++로 구현해보기 (0) | 2021.08.29 |
| 백준 1212번, 1373번, 8진수 2진수로 변환, 2진수 8진수로 변환 C++ (0) | 2021.08.28 |