포스트

Baekjoon 4949 - 균형잡힌 세상

Baekjoon 4949 - 균형잡힌 세상

문제


Example Input/Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// IN
So when I die (the [first] I will see in (heaven) is a score list).
[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
 . // 알파벳, 공백, 소괄호, 대괄호, 마지막 온점 (1 <= 길이 <= 100)
. // 입력 끝

// OUT
yes // 문자열 내 괄호가 균형잡혔는가?
yes
no
no
no
yes
yes

C++ 풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <algorithm>
#include <stack>

using namespace std;

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

    while (true)
    {
        string s;
        getline(cin, s);

        if (s == ".")
            break;

        stack<char> st;
        bool isBalanced = true;

        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;

        cout << (isBalanced ? "yes": "no") << '\n';
    }
}

메모


  • )] 입력받고 처리하는 부분 모양이 비슷해서 어떻게 합칠 수 있을까 고민
    • 아스키코드 표를 보고 (), [] 수 차이가 각각 1, 2인 것을 보고, diff <= 2로 괄호쌍 여부을 판단
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.