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

2025. 4. 19. 18:44

 


접근 방법

문제 9012번과 마찬가지로 stack을 활용하여 문제를 해결한다.

 

1. stack에는 ( 또는 [만 push로 들어간다.

2. ) 또는 ]이 나오면 pop을 통해 stack에서 꺼낸다.

3. 만일 pop을 했는데 문자열이 비어있거나 (와 [이 아니라면, 즉 짝이 아니라면 해당 문자열은 균형이 아니다.

4. 문자열을 전부 확인했는데 stack에 남은 괄호가 있으면 해당 문자열은 균형이 아니다.

 

import sys

while True:
    line = sys.stdin.readline().rstrip()
    if line == ".":
        break

    stack = []
    is_balance = True

    for l in line:

        if l == "(" or l == "[":
            stack.append(l)
        elif l == ")":
            if not stack or stack[-1] != "(":
                is_balance = False
                break
            stack.pop()
        elif l == "]":
            if not stack or stack[-1] != "[":
                is_balance = False
                break
            stack.pop()


    if is_balance and not stack:
        print("yes")
    else:
        print("no")

BELATED ARTICLES

more