1 분 소요

사용 언어: Python3

문제

괄호의 값

풀이

나의 풀이

# # 5:45
def isStack(strr):
    st = []
    for x in strr:
        if x == '(' or x == '[':
            st.append(x)
        elif x == ')':
            if st and st[-1] == '(':
                st.pop()
        elif x == ']':
            if st and st[-1] == '[':
                st.pop()
    if len(st) == 0:
        return True
    else:
        return False
    
op = input()
if not isStack(op):
    print(0)
else:
    stack = []
    for x in op:
        if x == '(' or x == '[':
            stack.append(x)

        elif x == ')':
            tmp = 1
            while stack and stack[-1] != '(': # '('가 아닌 동안
                tmp = int(stack[-1])
                stack.pop()
            stack.pop() # '(' 까지 pop
            tmp *= 2

            if stack and stack[-1].isdecimal(): # 숫자라면
                tmp += int(stack[-1])
                stack.pop() # 이미 있던 숫자 pop
            stack.append(str(tmp)) # 계산된 숫자 넣기

        elif x == ']':
            tmp = 1
            while stack and stack[-1] != '[': # '['가 아닌 동안
                tmp = int(stack[-1])
                stack.pop()
            stack.pop() # '[' 까지 pop
            tmp *= 3

            if stack and stack[-1].isdecimal(): # 숫자라면
                tmp += int(stack[-1])
                stack.pop() # 이미 있던 숫자 pop
            stack.append(str(tmp)) # 계산된 숫자 넣기

    print(int(stack[0]))
  • 테스트 케이스: 통과
  • 제출 결과: 런타임 에러
    스크린샷 2023-06-20 오후 6 58 26

다른 풀이

참고

op = input()

stack = []
answer = 0
tmp = 1

for i in range(len(op)):

    if op[i] == "(":
        stack.append("(")
        tmp *= 2

    elif op[i] == "[":
        stack.append("[")
        tmp *= 3

    elif op[i] == ")":
        if not stack or stack[-1] == "[":
            answer = 0 # 잘못된 괄호 -> 0 출력하기 위해
            break # for문 종료
        if op[i-1] == "(":
            answer += tmp
        stack.pop()
        tmp //= 2

    else:
        if not stack or stack[-1] == "(":
            answer = 0 # 잘못된 괄호 -> 0 출력하기 위해
            break # for문 종료
        if op[i-1] == "[":
            answer += tmp
        stack.pop()
        tmp //= 3

if stack: # stack에 값이 남아있으면 안된다
    print(0)
else:
    print(answer)
  • 테스트 케이스: 통과
  • 제출 결과: 통과
    스크린샷 2023-06-20 오후 7 15 03


💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기