CodingTest/Baekjun Online Judge

[ 백준 / BOJ ] 2504 괄호의 값

EEOOOO 2022. 7. 1. 02:08

/  첫 구현  /

 

from collections import deque
import sys

bracket = list(sys.stdin.readline().strip())
calc = []
so = 0
dae = 0
temp = deque([])
while bracket:
  now = bracket.popleft()
  if now == '(':
    calc.append(2)
    so += 1
    next = bracket.popleft()
    if next != ')': # 안에 뭐 있으면
      calc.append('x')
      calc.append('(')
      while so > 0:
        temp.append(next)
        if next ==
      
  elif now == '[':
    calc.append(3)
    dae += 1
    if bracket[0] != ']': # 안에 뭐 있으면
      calc.append('x')
      calc.append('(')

 

흐미.. 중도 포기했습니다. 이 구성으로 가면 안 될 것 같아서 ... ㅠㅜㅜ

 

그리고 검색해서 공부하고 오기로 했습니다.

 


 

https://westernriver.tistory.com/7

 

[백준] 2504. 구현_괄호의값 - Python

문제 4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.

westernriver.tistory.com

 

진짜.. 직관적으로 이해하기도 쉽고 구현도 쉽게 잘 구성하셨습니다..

 


 

유사 조건 하에 다양한 케이스가 있는 경우! 효율성 생각하며 알고리즘 구성할 욕심 내지 말고

경우의 수 다 나눠가며 일단 쭉 깔고, 가장 옳은 것 모아서 단순하게 가기!!

 


 

설명 읽고 풀이 내용 메모한 걸 바탕으로 작성한 코드입니다.

 

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)