[BOJ 3986] 좋은 단어

xeonu·2022년 7월 4일
0

코딩테스트

목록 보기
5/7
post-thumbnail

문제링크

소스코드

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

using namespace std;

int main() {

    string str;
    int n, cnt = 0;
    cin >> n;
    while (n--) {
        stack<char> st;
        cin >> str;
        for (char c: str) {
            if (!st.empty()) {
                if (st.top() == c) {
                    st.pop();
                    continue;
                }
            }
            st.push(c);
        }

        if (st.empty()) cnt++;
    }

    cout << cnt << endl;
}

스택의 대표문제일 괄호문제와 매우 유사하다. 스택의 top과 그 다음 문자가 동일하면 스택을 비워주고 그렇지 않다면 push 해준다.
최종적으로 스택이 비어있으면 이는 좋은 단어인 것이다.

profile
백엔드 개발자가 되기위한 여정

0개의 댓글