컴퓨터 사이언스/1고리즘

백준 4949 : 균형잡힌 세상

저세상 개발자 2021. 9. 8. 15:23

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

 

4949번: 균형잡힌 세상

하나 또는 여러줄에 걸쳐서 문자열이 주어진다. 각 문자열은 영문 알파벳, 공백, 소괄호("( )") 대괄호("[ ]")등으로 이루어져 있으며, 길이는 100글자보다 작거나 같다. 입력의 종료조건으로 맨 마

www.acmicpc.net

 

재귀나 스택으로 해결할 수 있는 문제다.

괄호가 나오면 스택에 넣어주고, 알맞은 닫는 괄호가 나오면 pop, 그렇지 않을 시 false를 리턴하는 식으로 구현했다.

 

#include <iostream>
#include <string>
#include <stack>

using namespace std;

bool check_validation(string& s) {
	int idx = 0;
	stack<char> st;

	while (idx < s.size()) {
		if (s[idx] == '(') st.push(1);
		else if (s[idx] == '[') st.push(2);
		else if (s[idx] == ')') {
			if (!st.empty() && st.top() == 1) st.pop();
			else return 0;
		}
		else if (s[idx] == ']') {
			if (!st.empty() && st.top() == 2) st.pop();
			else return 0;
		}
		++idx;
	}

	return st.empty() ? 1 : 0;
}

void solution() {
	string s;
	while (getline(cin, s) && s.compare(".")) {
		if (check_validation(s)) cout << "yes\n";
		else cout << "no\n";
	}
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	solution();

	return 0;
}
메모리: 2024 kb 시간: 4 ms