[백준]2304번/ 괄호의 값

Effy_ee·2024년 1월 23일
0

코딩테스트

목록 보기
89/118

📖문제
https://www.acmicpc.net/problem/2504

import sys

#올바른 괄호인지 판별하는 함수
def isitbracket(s):
    stack=[]
    for char in s:
        if char in ['(','[']: 	# (,[ 일 때 stack에 추가
            stack.append(char)
        else:				 	# ),] 일 때
            if not stack:       # 여는 괄호가 없으면 올바른 괄호가 아님
                return False
            if stack[-1]=='(' and char!=')': # (] 인 경우
                return False
            if stack[-1]=='[' and char!=']': #[) 인 경우
                return False
            stack.pop()					# (),[] 인 경우 스택에서 꺼내기
    if len(stack)!=0:		#stack에 남은 괄호가 있으면 올바른 괄호 아님
        return False
    else:					#stack에 남은 괄호가 없으면 올바른 괄호
        return True


# 계산을 수행하는 함수

def solution(s):
    stack=[]
    for char in s:
        if char in ['(','[']:
            stack.append(char)
        else:
            if char==')':				
                if stack[-1]=='(':
                    stack.pop()
                    stack.append(2)			#()인 경우 stack의 (를 꺼내고 2를 추가
                else:						# 스택의 맨 위 값이 '('이 아니면
                    temp=0   
                    while stack[-1]!='(' #스택의 맨 위 값이 '(' 될 때까지
                        temp+=stack.pop() #값을 더해주고
                    stack.pop()           #스택의 맨 위가 '(' 되면 꺼내고
                    stack.append(2*temp)  #() 사이의 값들을 더한것을 *2 해주기
            else:
                if stack[-1]=='[':
                    stack.pop()
                    stack.append(3)
                else:
                    temp=0
                    while stack[-1]!='[':
                        temp+=stack.pop()
                    stack.pop()
                    stack.append(3*temp)
    print(sum(stack))



s=sys.stdin.readline().rstrip()

if isitbracket(s):
    solution(s)
else:
    print(0)

0개의 댓글