Baekjoon 2504 - 괄호의 값

문제


Example Input/Output

// IN
(()[[]])([])

// OUT
28

C++ 풀이


#include <iostream>
#include <algorithm>
#include <stack>

using namespace std;

bool isBalanced(string);
void calc(stack<int> &, int);

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    string s;
    cin >> s;

    // Check Is Balanced
    if (isBalanced(s) == false)
    {
        cout << '0';
        return 0;
    }

    // 스택에 숫자를 다시 집어넣는 경우가 있어서 stack<char>를 쓰기 어려움
    stack<int> st;

    // 그래서 괄호도 숫자로 만듦 (균형잡힌 괄호 문자열라는 걸 위에서 확인했으므로)
    // -(각 괄호가 대표하는 숫자 = 계산되는 숫자 i.e. '(', ')' 계산에 2만 쓰임)
    const int PARENTHESES_NUM = -2;        // '(', ')' = -2
    const int SQUARE_BRACKETS_NUM = -3; // '[', ']' = -3

    for (auto c: s)
    {
        if (c == '(')
            st.push(PARENTHESES_NUM);
        else if (c == '[')
            st.push(SQUARE_BRACKETS_NUM);
        else if ((c == ')'))
            calc(st, PARENTHESES_NUM);
        else if ((c == ']'))
            calc(st, SQUARE_BRACKETS_NUM);
    }

    int totalSum = 0;
    int stackSize = st.size();
    for (int i = 0; i < stackSize; i++)
    {
        totalSum += st.top();
        st.pop();
    }

    cout << totalSum;
}

bool isBalanced(string s)
{
    bool _isBalanced = true;
    stack<char> st;
    for (auto c: s)
    {
        if ((c == '(') || (c == '['))
            st.push(c);
        else if ((c == ')') || (c == ']'))
        {
            if (st.empty() || (abs(c - st.top()) > 2))
            {
                _isBalanced = false;
                break;
            }

            st.pop();
        }
    }

    if (st.empty() == false)
        _isBalanced = false;

    return _isBalanced;
}

// '()', '[]', '(X)', '[X]', 'XY' 계산
void calc(stack<int> &st, int bracketNum)
{
    int sum = 0;
    while (true)
    {
        // '()', '[]', '(X)', '[X]'
        if (st.top() == bracketNum)
        {
            st.pop();
            st.push((sum == 0) ? -bracketNum: sum * -bracketNum);
            break;
        }
        // 'XY'
        else
        {
            sum += st.top();
            st.pop();
        }
    }
}

메모


  • 올바른 문자열인지 확인하는 과정을, 메인 계산 과정에 포함시키면 구현하기 어렵고 복잡할 것 같아서 메인 코드와 분리
  • 메인 코드는... 손으로 먼저 풀어보고 코드로 구현 (...)
    • 계산하면서 나오는 숫자를 스택에 다시 집어 넣는 방법

답글

답글을 불러오는 중...