백준 4949 : 균형잡힌 세상

혀니앤·2022년 3월 18일
0

C++ 알고리즘

목록 보기
109/118

https://www.acmicpc.net/problem/4949

1. 접근

  • 기존에 풀었던 괄호문제와 동일하게 풀면 된다.
  • 이 경우, 입력값에 공백이 포함되어 한줄이아닌 한 단어별로 입력이 받아졌는데, getline(cin,string) 함수를 사용해서 입력을 받아주었다.

2. 나의 풀이

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	while (1) {
		string input;
		getline(cin,input);
		stack<char> balance;

		bool IsAnswer = true;
		if (input == ".")	break;
		for (int i = 0; i < input.length(); i++) {
			if (input[i] == '(') {
				balance.push('(');
			}
			else if (input[i] == '[') {
				balance.push('[');
			}
			else if (input[i] == ')' || input[i] == ']') {
				if (balance.empty()) {
					IsAnswer = false;
					break;
				}
				if (input[i] == ')'&& balance.top()=='(') {
					balance.pop();
				}
				else if (input[i] == ']' && balance.top() == '[') {
					balance.pop();
				}
				else {
					IsAnswer = false;
					break;
				}
			}
		}
		if (!balance.empty())	IsAnswer = false;
		if(IsAnswer)	cout << "yes" << "\n";
		else cout << "no" << "\n";
	}
	
	return 0;
}
profile
일단 시작하기

0개의 댓글