순간을 성실히, 화려함보단 꾸준함을

Codeforces Raif Round 1 (Div. 1 + Div. 2) : C번 본문

알고리즘,SQL/codeforce 문제

Codeforces Raif Round 1 (Div. 1 + Div. 2) : C번

폭발토끼 2020. 10. 21. 09:40

codeforces.com/contest/1428/problem/C

 

Problem - C - Codeforces

 

codeforces.com

문제 : 문자열이 주어지고 문자열중 'AB'와 'BB'가 존재한다면 증발한다. 이 작업을 반복하여 실행할 때 문자열을 최소로 만들어서 길이를 구하는 문제이다.

//참고로 백준문제 : 문자열 폭발 과 동일한 문제이다.

 

해설 : stack을 이용하면 된다. 하나씩 넣고 조건에 맞는 문자열이라면 pop 해주는 식으로.

 

#include<bits/stdc++.h>
 
using namespace std;
using ll = long long;
 
int arr[2][300010];
 
void solve();
 
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
 
	int t;
	cin >> t;
	while (t--)
		solve();
	return 0;
}
void solve()
{
	string str;
	stack<char> s;
 
	cin >> str;
 
	for (int i = 0; i < str.length(); i++)
	{
		if (s.empty())
			s.push(str[i]);
		else {
			if (s.top() == 'A' && str[i] == 'B')
				s.pop();
			else if (s.top() == 'B' && str[i] == 'B')
				s.pop();
			else
				s.push(str[i]);
		}
	}
	cout << s.size() << "\n";
}