백준 3986 : 좋은 단어

혀니앤·2022년 3월 8일
0

C++ 알고리즘

목록 보기
107/118

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

1. 접근

  • 괄호맞추기 문제처럼 짝을 맞춰야하는 문제에서는 stack이 유리하다.
  • 가장 가까운곳과 짝을짓는게 겹칠 위험이 덜하기때문에, stack에 넣고 그때의 top값과 같다면 짝을지어주면 된다.
  • 만약 모든 문자를 돌았는데 스택이 비어있지않다면 좋은 단어가 아니다.
  • A와 B의 개수가 다르거나, 단어의 길이가 홀수여도 좋은 단어가 아니다.

2. 나의 풀이

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

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

	int n;
	cin >> n;

	int ret = 0;
	while (n-- > 0) {
		string s; cin >> s;

		bool IsGood = true;
		int count[2] = { 0,0 };
		stack<char> stack;

		if (s.length() % 2 == 1) continue;
		for (int i = 0; i < s.length(); i++) {
			count[s[i] - 'A']++;
			if (!stack.empty()) {
				if (stack.top() == s[i]) {
					stack.pop();
					continue;
				}
				else {
					stack.push(s[i]);
				}
			}
			else stack.push(s[i]);
		}
		if (!stack.empty())	IsGood = false;
		if (count[0] % 2 != 0 || count[1] % 2 != 0)	IsGood = false;
		if (IsGood)	ret++;
	}

	cout << ret << "\n";
	return 0;
}
profile
일단 시작하기

0개의 댓글