코딩테스트/백준
[백준] 2504번 괄호의 값 / 파이썬(python)
Jiwon_C
2021. 5. 14. 19:57
# 문제 링크
https://www.acmicpc.net/problem/2504
2504번: 괄호의 값
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일
www.acmicpc.net
# Soultion
여러가지 경우의 수를 잘 생각해야 하는 문제이다.
나는 test case가 '(()([())])'인 경우에 0이 나와야하는데 28이 나오는 반례를 해결했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
s = input()
stack = []
for i in s:
if i in ['(','[']:
stack.append(i)
else:
if stack and i==')':
if len(stack)>1 and str(stack[-1]).isdigit():
n = stack.pop()*2
stack.pop()
stack.append(n)
elif stack[-1]=='(':
stack.pop()
stack.append(2)
else:
stack.append('-')
break
elif stack and i==']':
if len(stack)>1 and str(stack[-1]).isdigit():
n = stack.pop()*3
stack.pop()
stack.append(n)
elif stack[-1]=='[':
stack.pop()
stack.append(3)
else:
stack.append('-')
break
else:
stack.append('-')
break
if len(stack)>1 and str(stack[-1]).isdigit() and str(stack[-2]).isdigit():
stack.append(stack.pop()+stack.pop())
if len(stack)==1 and str(stack[-1]).isdigit():
print(stack.pop())
else:
print(0)
|
cs |