DevLog:-)

[알고리즘][파이썬]2504-괄호의 값 본문

알고리즘/백준

[알고리즘][파이썬]2504-괄호의 값

hyeon200 2023. 5. 14. 00:29
반응형

문제

코드

import sys

def x(s,n):
     if(s ==')'):
          return 2*n
     elif(s==']'):
        return 3*n

def check(s):
    stack = []
    for i in s:
        sum =0    
        if i =='(':
            stack.append(')') 
        elif i =='[':
            stack.append(']')     #열린 괄호 들어오면 stack에 닫힌 괄호 넣음
        elif not stack:
            return 0
        elif stack[-1] == i:
            stack.pop()
            if i ==')': stack.append('2')
            else: stack.append('3')
        elif stack[-1] != ')'and stack[-1]!=']':
            if(i not in stack):
                return 0
            while(stack[-1]!=')'and stack[-1]!=']'):
                sum += int(stack.pop())
            if(not stack or stack.pop()!=i):
                return (0)
            stack.append(str(x(i,sum)))
    sum =0
    if(')' in stack or ']' in stack ):
        return (0)
    else:
        while(stack):
            sum +=int(stack.pop())
        return sum
            

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

print(check(s))

Comments

스택을 이용하여 풀었다.

 

 

[풀면서 발생했던 오류💦]

 

오류1

-문자열 뒤에 개행 처리

 s= sys.stdin.readline() -> 오류메세지: list index out of range #print(type(s))->str #print(len(s))->13

해결 s = sys.stdin.readline().strip()

 

-strip():

문자열 맨 앞과 맨 끝의 공백문자를 제거해준다.

문자열 뒤에 공백을 제거 하지 않고 함수를 돌리면 stack의 끝이 개행이 되니까 stack[-1]에서 오류가 발생한다.

 

오류2

),] : 닫히는 괄호 젤 먼저 올 경우 오류 발생

elif not stack: return 0

코드 추가

 

오류3

(())) : 앞에 다 맞고 뒤에 닫히는 괄호 올 경우 오류 발생

4번째 if 문에 

if(i not in stack): return 0

코드 추가

반응형