[알고리즘] 백준 3986

dlwl98·2022년 5월 17일
0

알고리즘공부

목록 보기
5/34
post-thumbnail

백준 3986번

해결 과정 요약

문자열의 첫 문자를 스택에 push하고
두번째 문자부터는 스택의 맨 위의 값과 같으면 pop을 해주고 다르면 push해준다.
문자열 끝까지 push 또는 pop을 완료했을 때
스택이 비어있다면 '좋은단어'이고, 비어있지 않다면 '좋은단어'가 아니다.

풀이

#include <bits/stdc++.h>
using namespace std;

stack<char> s;
int N, ret;
string com;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    cin >> N;
    for(int i=0; i<N; i++){
        cin >> com;
        for(int j=0; j<com.size(); j++){
            if(!s.empty()){
                if(s.top() == com[j]){
                    s.pop();
                    continue;
                }
            }
            s.push(com[j]);
        }
        if(s.empty()) ret++;
        else while( !s.empty() ) s.pop();
    }
    cout << ret << "\n";
    
    return 0;
}

0개의 댓글