본문 바로가기

CodingTest/Baekjun Online Judge

[ BOJ / 파이썬 ] 2504 괄호의 값

음.. sum 값을 따로 빼주는 생각을 못 했다. 

쉬울 줄 알았는데 은근 까다로운 문제다..

 

/  제출 1  /

import sys
input = sys.stdin.readline


brackets = list(input())

stack = []
num = 1
sum = 0
for b in brackets:
  if b == '(':
    stack.append(b)
    num *= 2

  elif b == '[':
    stack.append(b)
    num *= 3

  elif b == ')':
    if not stack or stack[-1] != '(':
      sum = 0
      break
    if stack[-1] == '(':
      sum += num
      stack.pop()
      num //= 2

  elif b == ']':
    if not stack or stack[-1] != '[':
      sum = 0
      break
    if stack[-1] == '[':
      sum += num
      stack.pop()
      num //= 3
  print(stack, sum) 
if stack:
  sum = 0
print(sum)

: 답이 제대로 안 나온다.. 왜..? ㅠㅜㅜㅠㅜㅠㅜ

: 아니 왜 또 이틀만에 코테 실력이 또 하락세야..? ㅠㅠㅠ

 

이 문제는 심지어 한 달 전에 풀어서 맞춘 문제인데도 답을 못 내겠다..

 

def isperfect(word):
  word_list = []

  for i in word:
    if not word_list and (i == ']' or i == ')'):
      return False
    if i == '[' or i == '(':
      word_list.append(i)
    elif i == ')' and word_list[-1] == '(':
      word_list.pop()
    elif i == ']' and word_list[-1] == '[':
      word_list.pop()
  if len(word_list) > 0:
    return False
  return True

def calculate(word):
  sum_list = []
  for i in word:
    if i == '(' or i == '[':
      sum_list.append(i)
    elif i ==')':
      if sum_list[-1] == '(':
        sum_list.pop()
        sum_list.append(2)
      else:
        partial_sum = 0
        for j in range(len(sum_list) - 1, -1, -1):
          if type(sum_list[j]) == int:
            partial_sum += sum_list[j]
            sum_list.pop()
          elif sum_list[j] == '(':
            sum_list.pop()
            break
        sum_list.append(partial_sum * 2)
    elif i == ']':
      if sum_list[-1] == '[':
        sum_list.pop()
        sum_list.append(3)
      else:
        partial_sum = 0
        for j in range(len(sum_list) - 1, -1, -1):
          if type(sum_list[j]) == int:
            partial_sum += sum_list[j]
            sum_list.pop()
          elif sum_list[j] == '[':
            sum_list.pop()
            break
        sum_list.append(partial_sum*3)
  return sum(sum_list)


string = list(input().strip())
if isperfect(string):
  result = calculate(string)
  print(result)
else:
  print(0)

: 이게 한 달 전 정답 풀이인데.. 너무 길고 복잡해서 좀 간단하게 하려했더니.. 안 ㅣ된다.. 하...