[파이썬] 백준 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)
'Algorithm > Data Structures' 카테고리의 다른 글
[파이썬] 백준 28078 : 중력 큐 (골드5) (0) | 2025.05.21 |
---|---|
[파이썬] 백준 1976 : 여행 가자 (골드4) (0) | 2025.04.23 |
[파이썬] 백준 10775 : 공항 (골드2) (0) | 2025.04.23 |
[파이썬] SWEA 5653 : 줄기세포배양(test) (0) | 2025.04.15 |
[파이썬] 백준 11000 : 강의실 배정 (골드5) (0) | 2025.04.06 |
[파이썬] 백준 6549 : 히스토그램에서 가장 큰 직사각형 (플레5) (0) | 2025.04.06 |
[파이썬] 백준 1863 : 스카이라인 쉬운거 (골드4) (0) | 2025.03.30 |
댓글