본문 바로가기
  • 초부득3 - 어제보다 나은 내일을 위해
  • 꿈이 현실이 되는 날까지
sw사관학교 정글 2기/02 이분탐색, 분할정복, 스택, 큐, 우선순위 큐

[스택] 백준 2504번 괄호의 값 with Python3

by 금의야행 2021. 8. 16.

https://www.acmicpc.net/problem/2504

 

2504번: 괄호의 값

4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.  만일

www.acmicpc.net

문제

정답 풀이

import sys

str = sys.stdin.readline().rstrip()

stack = list()

for i in str:

    if i == ")":
        temp = 0

        while stack:  # stack에 element가 있다면
            top = stack.pop()
            if top == "(":
                if temp == 0:
                    stack.append(2)
                else:
                    stack.append(2 * temp)
                break

            elif top == "[":  # ([)] 같은 경우는 올바르지 못한 괄호열이기에
                print("0")  # 0을 출력하고
                exit(0)  # 프로그램을 바로 종료시킨다
            else:  # 숫자가 나온다면
                if temp == 0:
                    temp = int(top)  # temp를 업데이트한다
                else:
                    temp = temp + int(top)

    elif i == "]":
        temp = 0

        while stack:
            top = stack.pop()
            if top == "[":
                if temp == 0:
                    stack.append(3)
                else:
                    stack.append(3*temp)
                break
            elif top == "(":
                print(0)
                exit(0)
            else:
                if temp == 0:
                    temp = int(top)
                else:
                    temp = temp + int(top)
    else:
        stack.append(i)


result = 0
#마지막에 숫자만 남았을때 서로 더해줘서 결과값을 만든다.
for i in stack:
    if i == "(" or i == "[":
        print(0)
        exit(0)
    else:
        result += i

print(result)

출처:https://chocodrogba.tistory.com/9

 

해석

 

댓글