Algorithm/프로그래머스

[프로그래머스] 올바른 괄호 with C++

nowkoes 2023. 5. 28. 00:00

문제 설명


제한 사항 및 입출력 예제


개념

 대괄호가 올바르게 짝지어졌는지 확인하는 문제다. 스택을 사용하는 대표적인 문제로서 특정 조건을 만족할 때 스택에서 문자를 뽑아서 스택이 비었는지 여부를 체크하면 쉽게 해결할 수 있다. 


풀이

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

bool solution(string s)
{
    stack<char> st;
    bool answer = true;

    for (const auto& ch : s)
    {
        if (st.empty())
            st.push(ch);

        else if (st.top() == '(' && ch == ')')
            st.pop();

        else
            st.push(ch);
    }

    if (!st.empty())
        answer = false;

    return answer;
}
반응형