Little Jay

[C++] 백준 4889번 - 안정적인 문자 본문

알고리즘/BOJ

[C++] 백준 4889번 - 안정적인 문자

Jay, Lee 2021. 8. 17. 17:44

'{'가 들어오면 push하고

'}'가 들어올 때는 먼저 stack이 비었는지 확인하고

비어있으면 '{'로 바꿔주고 바꾼 횟수를 늘려준다

만약 empty가 아니라면 pop해주면 된다

 

스택이 비었으면 return change

스택이 차 있으면 return change + st.size() / 2

 

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

int main() {

	string s;
	int test = 1;
	while (true) {
		cin >> s;
		int change = 0;

		if (s[0] == '-')
			break;

		stack<char> st;
		for (int i = 0; i < s.length(); i++) {
			if (s[i] == '{')
				st.push(s[i]);
			else {
				if (st.empty()) {
					st.push('}');
					change++;
				}
				else
					st.pop();
			}
		}


		if (st.empty()) {
			cout << test << ". " << change << "\n";
		}
		else {
			cout << test << ". " << change + (st.size() / 2) << "\n";
		}

		test++;
	}


}
Comments