[실버2] 2504번 : 괄호의 값

Quesuemon·2021년 4월 9일
0

코딩테스트 준비

목록 보기
72/111

🛠 문제

https://www.acmicpc.net/problem/2504


👩🏻‍💻 해결 방법

stack을 사용해 문제를 해결할 수 있다
'(', '['일 경우는 우선 stack에 추가해주고, ')', ']'일 경우는 값을 더할 때와 곱할 때를 나누어 구현해주었다
도중에 짝이 맞지 않는 괄호를 만나거나 for문을 다 돌았는데 stack에 괄호가 남아있을 경우에는 0을 출력하고 바로 프로그램을 종료하였다

소스 코드

string = list(input())
stack = []
answer = 0

for s in string:
  if s == ')':
    t = 0
    while len(stack) != 0:
      top = stack.pop()
      if top == '(':
        if t == 0:
          stack.append(2)
        else:
          stack.append(2*t)
        break
      elif top == '[':
        print(0)
        exit(0)
      else:
        t = t + int(top)
  elif s == ']':
    t = 0
    while len(stack) != 0:
      top = stack.pop()
      if top == '[':
        if t == 0:
          stack.append(3)
        else:
          stack.append(3*t)
        break
      elif top == '(':
        print(0)
        exit(0)
      else:
        t = t + int(top)
  else:
    stack.append(s)

for i in stack:
  if i == '(' or i == '[':
    print(0)
    exit(0)
  else:
    answer += i

print(answer)

💡 다른 사람의 풀이

재귀를 사용한 문제 풀이다

import sys
input = sys.stdin.readline

s = list(input().rstrip())[::-1]

def cal(start):
    r = 0
    while s:
        a = s.pop()
        if a == "(" or a == "[":
            r += cal(a)
        elif start == "(" and a == ")":
            return 2 * max(1,r)
        elif start == "[" and a == "]":
            return 3 * max(1,r)
    
    # 리스트가 비었는데 최종 return 하지 못했다는 것은 괄호에 문제가 있음을 의미
    print(0)
    sys.exit()

ans = 0    
while s:
    ans += cal(s.pop())
print(ans)

0개의 댓글