BOJ4949

김현민·2021년 1월 20일
0

Algorithm

목록 보기
9/126
post-thumbnail

BOJ4949. 균형잡힌 세상

문제


코드1

#include <iostream>
#include <stack>
#include <vector>

using namespace std;

int main(int argc, char const *argv[])
{
    vector<char> v;
    string str;
    int idx = -1;
    while (1)
    {
        getline(cin, str);
        v.clear();

        if (str == ".")
            return 0;

        for (int i = 0; str[i] != '\0'; i++)
        {
            if (str[i] == '(' || str[i] == '[' || str[i] == ')' || str[i] == ']')
            {
                char temp = str[i];
                v.push_back(temp);
                // cout << idx << ' ' << v.at(idx) << endl;
                idx++;
                if (temp == ')')
                {
                    if (v[idx - 1] == '(')
                    {

                        v.pop_back();
                        v.pop_back();
                        idx -= 2;
                    }
                }
                else if (temp == ']')
                {
                    if (v[idx - 1] == '[')
                    {
                        v.pop_back();
                        v.pop_back();
                        idx -= 2;
                    }
                }
            }
        }

        if (v.size() < 1 || str == " .")
        {
            cout << "yes" << '\n';
        }
        else
        {
            cout << "no" << '\n';
        }
    }
    return 0;
}
  • 스택을 사용하다가 벡터로 시도해봄
    모든 모양의 괄호를 하나씩 넣고, 바로 앞전에 괄호가 짝이 맞으면 pop, pop 하는 방식.
    이 과정을 모두 거쳐 벡터 크기가 0이면 yes 아니면 no를 출력한다.



코드2

#include <iostream>
#include <stack>

using namespace std;

int main(int argc, char const *argv[])
{

    while (1)
    {
        stack<char> st;
        string str;
        getline(cin, str);

        if (str == ".")
            return 0;
        int flag = 0;
        for (int i = 0; i < str.size(); i++)
        {
            char temp = str[i];
            if (temp == '(' || temp == '[')
            {
                st.push(temp);
            }
            else if (temp == ')')
            {
                if (st.empty() || st.top() != '(')
                {
                    flag = 1;
                    break;
                }
                st.pop();
            }
            else if (temp == ']')
            {
                if (st.empty() || st.top() != '[')
                {
                    flag = 1;
                    break;
                }
                st.pop();
            }
        }

        if (flag || !st.empty())
        {
            cout << "no" << '\n';
        }
        else
        {
            cout << "yes" << '\n';
        }
    }
    return 0;
}
  • 왼괄호만 넣고 오른쪽괄호가 나오면 비교해서 pop을 한번만 해도 된다.
    그리고, flag를 써서 )(와 같은 경우도 대비함.

flag를 잘 써봐야겟다..

profile
Jr. FE Dev

0개의 댓글