코딩테스트/백준

[백준] 4949번 균형잡힌 세상 (C++)

Deff_a 2025. 1. 7. 11:30

문제

풀이

getline 함수를 이용하여, 공백을 포함하여 입력을 받은 뒤, Stack을 이용하여 균형잡인 문자열인지 판단했다.

 

이때, stack에 임의 값 '0'를 삽입(empty 처리를 피하기 위해)하고 모든 연산이 끝난 뒤, stack의 크기가 1일 경우에 yes, 아니라면 no를 출력한다.

#include <bits/stdc++.h>

using namespace std;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	while(true)
	{
		string input;
		getline(cin, input);
		if(input == ".")
			break;

		stack<char> stack;
		stack.push('0');
		
		for(int i = 0; i < input.length(); i++)
		{
			char c = input[i];
			if(!(c == '(' || c == ')' || c == '[' || c == ']')) continue;
			
			if((c == ')' && stack.top() == '(') || (c == ']' && stack.top() == '[')){
				stack.pop();
			}
			else
			{
				stack.push(c);
			}
		}
		
		string output = stack.size() == 1 ? "yes\n" : "no\n";
		cout << output;
	}
	return 0;
}