본문 바로가기

코딩테스트

목표2-2.백준2504번 괄호의 값

오늘의 문제

 

import sys

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

stack = list()

for i in input:
    if i == ")":
        temp = 0
        while stack:
            top = stack.pop()
            if top == "(":
                if temp == 0:
                    stack.append(2)
                else:
                    stack.append(2*temp)
                break
            elif top == "[":
                print(0)
                exit(0)
            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:
                   temp = temp + int(top)
    else:
        stack.append(i)
r = 0

for i in stack:
    if i=="(" or i == "[":
        print(0)
        exit(0)
    else:
        r += i

print(result)

list를 stack처럼 활용해서 푸는게 핵심이고, temp라는 변수에 [], ()에 따라 연산할 숫자를 넣어 마지막 for 문에서 더해줘야 한다.

 

ex)    (()) 와 같이 2x2를 해야 하는 상황은 stack에 ["(",2] 로 저장되어 있는 상태에서 ")"를 만났을 때이다.

temp라는 변수에 저장된 값에 )를 만나 완전한 괄호가 되면 *2를 해주는 것도 중요 포인트다.

 

아래 블로그에 정리가 잘 되어 있어 참고하였다.

chocodrogba.tistory.com/9