-
[백준] 2504번_괄호의값Study/알고리즘 2020. 1. 15. 18:42
문제 링크 : https://www.acmicpc.net/problem/2504
2504번: 괄호의 값
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일 X가 올바른 괄호열이면 ‘(X)’이나 ‘[X]’도 모두 올바른 괄호열이 된다. X와 Y 모두 올바른 괄호열이라면 이들을 결합한 XY도 올바른 괄호열이 된다. 예를 들어 ‘(()[[]])’나 ‘(())[][]’ 는 올바른 괄호열이지만 ‘([)]’ 나 ‘(()(
www.acmicpc.net
stack = [] bracket = input() stack.append(bracket[0]) point = 1 while point<len(bracket): new_ele = bracket[point] if new_ele == ")": try: if stack[-1] == "(": stack.pop() stack.append(2) elif str(stack[-1]).isdigit() and stack[-2] == "(": tmp = stack.pop() stack.pop() stack.append(tmp*2) except IndexError: stack.append(new_ele) elif new_ele == "]": try: if stack[-1] == "[": stack.pop() stack.append(3) elif str(stack[-1]).isdigit() and stack[-2] == "[": tmp = stack.pop() stack.pop() stack.append(tmp*3) except IndexError: stack.append(new_ele) else: stack.append(new_ele) if len(stack)>=2: if str(stack[-1]).isdigit() and str(stack[-2]).isdigit(): tmp = stack.pop() tmp += stack.pop() stack.append(tmp) point += 1 flag = True for ele in stack: if ele == "(" or ele==")" or ele=="[" or ele=="]": print(0) flag = False break if flag: print(stack[0])
하드 코딩이라 좀 더러워서 다시 고쳐봐야지
'Study > 알고리즘' 카테고리의 다른 글
[백준] 1759번_암호만들기 (0) 2020.01.17 [백준] 6359번_만취한상범 (0) 2020.01.17 [백준] 2675번_문자열반복 (0) 2020.01.15 [백준] 10809번_알파벳찾기 (0) 2020.01.15 [백준] 11720번_숫자의합 (0) 2020.01.15