mo1lusca의 블로그
[백준] 3986 좋은 단어 - C++ 본문
https://www.acmicpc.net/problem/3986
9012 괄호 문제와 비슷한 느낌으로 풀면 된다.
들어오는 문자를 stack에 push한다. (push하려고 준비 한다)
이때 만약 들어온 문자가 top에 있던 문자와 같은 문자라면 pop한다.
#include <iostream>
#include <stack>
using namespace std;
int main() {
int n;
cin >> n;
int cnt = 0;
for (int i = 0; i < n; i++) {
stack<char> s;
string buf;
cin >> buf;
int len = buf.length();
for (int j = 0; j < len; j++) {
if (s.empty()) {
s.push(buf[j]);
}
else if (s.top() == buf[j]) {
s.pop();
}
else {
s.push(buf[j]);
}
}
if (s.empty()) {
cnt++;
}
}
cout << cnt;
return 0;
}
한 문자열에 대해 위에서 말한 작업을 수행 후 stack이 empty인지 검사한다.
empty이면 좋은 단어이므로 cnt를 증가시킨다.
'PS' 카테고리의 다른 글
| [백준] 14729 칠무해 - C++ (0) | 2025.06.01 |
|---|---|
| [백준] 1966 프린터 큐 - C++ (0) | 2025.06.01 |
| [백준] 9012 괄호 - C++ (1) | 2025.06.01 |
| [백준] 1181 단어 정렬 - Rust (0) | 2025.05.27 |
| [백준] 1697 숨바꼭질 - C (0) | 2025.05.18 |