Algorithm/noj.am

[Python] 백준 2504번 - 괄호의 값

SweetDev 2021. 7. 14. 15:09
# 2504 괄호의 값
str = input()

# 맞는지 검증
stack = []
for index, char in enumerate(str):
    if char == '(':
        stack.append('(')
    elif char == '[':
        stack.append('[')
    elif char == ')':
        if len(stack) > 0:
            ret = stack.pop()
            if ret != '(':
                print("0")
                exit(0)
        else:
            print("0")
            exit(0)
    elif char == ']':
        if len(stack) > 0:
            ret = stack.pop()
            if ret != '[':
                print("0")
                exit(0)
        else:
            print("0")
            exit(0)

if len(stack) !=0:
    print("0")
    exit(0)

# count 계산하기
out = ""
index = 0
char = ""
while True:
    if index >= len(str):
        # print(out)
        print(eval(out))
        exit(0)

    char = str[index]
    if char == "(" and (str[index + 1] == "(" or str[index + 1] == "["):
        out += "+2*("
        index += 1
    elif char == "(" and str[index + 1] == ")":
        out += "+2"
        index += 2

    elif char == "[" and (str[index + 1] == "(" or str[index + 1] == "["):
        out += "+3*("
        index += 1
    elif char == "[" and str[index + 1] == "]":
        out += "+3"
        index += 2

    elif char == ")":
        out += ")"
        index += 1
    elif char == "]":
        out += ")"
        index += 1