괄호의 값 구하기
입력 | 출력 |
---|---|
(()[[]])([]) | 28 |
[][]((]) | 0 |
: 스택을 사용한다는 것은 너무나 자명. 문제는 어떨 때 더하고 어떨 때 곱할 것인가?
- '(' 나 '[' 일 때 스택에 저장
- ')'일 때 '('를 만날때까지 pop해서 숫자들만 더해
- top원소가 '('이어서 더할 값이 없으면 2 저장
- 더한 최종 수에 2를 곱한 수를 스택에 다시 저장
- ']'일 때 '['를 만날때까지 pop해서 숫자들만 더해
- top원소가 '('이어서 더할 값이 없으면 3 저장
- 더한 최종 수에 3을 곱한 수를 스택에 다시 저장
sen = input()
stack = []
ans = 0
for s in sen:
if s == '(' or s == '[':
stack.append(s)
elif s == ')':
while stack:
if stack[-1] == '(':
if ans == 0:
stack.pop()
stack.append(2)
else:
stack.pop()
stack.append(ans*2)
ans = 0
break
elif isinstance(stack[-1], int):
ans += stack.pop()
else:
print("0")
exit()
elif s == ']':
while stack:
if stack[-1] == '[':
if ans == 0:
stack.pop()
stack.append(3)
else:
stack.pop()
stack.append(ans*3)
ans = 0
break
elif isinstance(stack[-1], int):
ans += stack.pop()
else:
print("0")
exit()
answer = 0
for s in stack:
if isinstance(s, int):
answer += s
else:
print("0")
exit()
print(answer)
isinstance(원소, int)
: 정수인지 확인exit()
: 프로그램 끝내기