본문 바로가기
Algorithm/Data Structures

[파이썬] 백준 2504 : 괄호의 값 (골드5)

by 베짱이28호 2025. 5. 18.

[파이썬] 백준 2504 : 괄호의 값 (골드5)

[백준 2504 : 괄호의 값](2504번: 괄호의 값)


풀이

방향성 생각

닫는 괄호가 일치할 때 스택에 int만 쌓여있는 경우는 전부 temp에 더해줘서 누적값 구하기.

int를 전부 터뜨리고도 stack이 남았으면 그 괄호는 현재 닫는 괄호와 일치하는 여는 괄호이므로 제거하기.

코드

stack = []
string = input().strip()
if string.count('[') != string.count(']') or string.count('(') != string.count(')'):
    print(0)
    exit()

for s in string:
    if s in '([':
        stack.append(s)
    else:
        if not stack or (stack[-1]== '[' and s == ')') or (stack[-1] == '(' and s == ']'):
            break
        temp = 0
        while stack and isinstance(stack[-1],int):
            temp += stack.pop()
        if stack:
            stack.pop()
        scale = 2 if s == ')' else 3
        stack.append(scale if not temp else temp*scale)

try:
    print(sum(stack))
except:
    print(0)

댓글