[백준] 4949번 : 균형잡힌 세상

김개발·2021년 9월 23일
0

백준

목록 보기
26/75

문제 푼 날짜 : 2021-09-22

문제

문제 링크 : https://www.acmicpc.net/problem/4949

접근 및 풀이

우선, 문자열에 공백도 같이 들어오기 때문에 getline으로 입력을 받아주었다.
많은 문제를 풀다보니 괄호의 짝을 맞추는 문제가 등장하면 반사적으로 stack을 이용해서 풀고 있다.
열린괄호 ('(', '[') 가 들어오면 stack 에 넣어주고, 닫힌 괄호(')', ']')가 나오면 그 stack의 top에 짝이되는 괄호가 있는지 체크해주면 된다.
마지막에 stack이 비어있는지 여부도 체크해줬어야 했는데, 이 부분을 놓쳐서 계속 실패를 해버렸다. 왜냐하면 틀린 코드에서는 입력으로 닫힌 괄호 없이 열린 괄호만 주어진다면 잘못된 정답을 출력하게 되기 때문이다.

코드(틀림)

// 백준 4949번 : 균형잡힌 세상
#include <iostream>
#include <stack>

using namespace std;

int main() {
    while (true) {
        string text = "";
        getline(cin, text);

        if (text == ".") {
            break;
        }

        stack<char> st;
        bool flag = true;
        for (int i = 0; i < text.length(); i++) {
            char ch = text[i];
            if (ch == '(' || ch == '[') {
                st.push(ch);
            } else if (ch == ')') {
                if (st.empty() || st.top() != '(') {
                    flag = false;
                    break;
                } else {
                    st.pop();
                }
            } else if (ch == ']') {
                if (st.empty() || st.top() != '[') {
                    flag = false;
                    break;
                } else {
                    st.pop();
                }
            }
        }
        if (flag) {
            cout << "yes" << '\n';
        } else {
            cout << "no" << '\n';
        }
    }
    return 0;
}

코드(통과)

// 백준 4949번 : 균형잡힌 세상
#include <iostream>
#include <stack>

using namespace std;

int main() {
    while (true) {
        string text = "";
        getline(cin, text);

        if (text == ".") {
            break;
        }

        stack<char> st;
        bool flag = true;
        for (int i = 0; i < text.length(); i++) {
            char ch = text[i];
            if (ch == '(' || ch == '[') {
                st.push(ch);
            } else if (ch == ')') {
                if (st.empty() || st.top() != '(') {
                    flag = false;
                    break;
                } else {
                    st.pop();
                }
            } else if (ch == ']') {
                if (st.empty() || st.top() != '[') {
                    flag = false;
                    break;
                } else {
                    st.pop();
                }
            }
        }
        if (flag && st.empty()) {
            cout << "yes" << '\n';
        } else {
            cout << "no" << '\n';
        }
    }
    return 0;
}

결과

피드백

테스트 케이스중에 예외 케이스에 대해 한 번 더 생각해보는 습관을 가지자.

profile
개발을 잘하고 싶은 사람

0개의 댓글