호지

[프로그래머스] 짝지어 제거하기 c++ 본문

알고리즘/프로그래머스

[프로그래머스] 짝지어 제거하기 c++

_hoji

 

stack을 이용하면 된다.

stack에 원소를 push하면 짝일 경우는

해당 원소가 stack의 top인지 확인하면 되므로,

짝이면 stack에서 pop하고

아닐 경우 stack에 push하면

마지막에 stack이 비어있다면 짝지어 모두 제거가 된 것이고

아니라면 남아있는 원소가 있다는 것이다.

 

 

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

int solution(string s)
{
    int answer = 0;
    if(s.size() % 2 == 1)
        return answer;
    stack<char> st;
    for(int i=0; i<s.size(); i++){
        if(!st.empty()){
            if(st.top() == s[i])
                st.pop();
            else
                st.push(s[i]);
        }
        else{
            st.push(s[i]);
        }
    }
    if(st.empty())
        answer = 1;
    return answer;
}
Comments