문제 : https://www.acmicpc.net/problem/2504
import sys
input = sys.stdin.readline
brackets = list(input().strip())
stack=[]
# 유효한 괄호열인지 확인
for brkt in brackets:
if stack:
if stack[-1] == '(' and brkt == ')':
stack.pop()
continue
elif stack[-1] == '[' and brkt == ']':
stack.pop()
continue
stack.append(brkt)
if stack:
print(0)
else:
for brkt in brackets:
if brkt == ')':
if stack[-1] == '(':
stack.pop()
stack.append(2)
else:
piece = 0
while(stack[-1] != '('):
piece += stack.pop()
stack.pop()
stack.append(2 * piece)
elif brkt == ']':
if stack[-1] == '[':
stack.pop()
stack.append(3)
else:
piece = 0
while(stack[-1] != '['):
piece += stack.pop()
stack.pop()
stack.append(3 * piece)
else:
stack.append(brkt)
print(sum(stack))
유효한 괄호열인거 확인하면
스택에 하나씩 넣으면서 ()나 []이 만들어지면 숫자 만들기.
숫자 안 만들어지는 오른쪽 괄호 나오면 왼쪽 괄호 나올 때까지
숫자 다 더한 후 괄호 종류 따라 x2 or x3
다 끝나면 숫자만 남으니까 sum
'📝 Study Notes > Baekjoon' 카테고리의 다른 글
3190 뱀 (Python) (0) | 2024.08.20 |
---|---|
17298 오큰수 (Python) (0) | 2024.08.17 |
1388 바닥 장식 (Python) (0) | 2024.07.23 |
18352 특정 거리의 도시 찾기 (Python) (0) | 2024.07.23 |
1260 DFS와 BFS (Python) (0) | 2024.07.23 |