오늘의 문제
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를 해주는 것도 중요 포인트다.
아래 블로그에 정리가 잘 되어 있어 참고하였다.
'코딩테스트' 카테고리의 다른 글
구현1. 백준2438번 별찍기 (0) | 2021.05.05 |
---|---|
코딩테스트 파이썬 주요 문법 정리 (0) | 2021.05.05 |
목표2-1.백준14888번 재귀 탐색의기본:연산자 끼워넣기 (0) | 2021.05.03 |
[CodeUp]Python기초100제 6091~6098 (0) | 2021.05.02 |
1-11목표.백준 2581번 소수 (0) | 2021.04.29 |