소프트웨어에 대한 모든 것

LeetCode 풀기 - 227. Basic Calculator II 본문

알고리즘/LeetCode

LeetCode 풀기 - 227. Basic Calculator II

앤테바 2021. 12. 28. 11:22
반응형

227. Basic Calculator II

https://leetcode.com/problems/basic-calculator-ii/

 

Basic Calculator II - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) 스택

 

class Solution:
    def calculate(self, s: str) -> int:
        def update(op, num):
            if op == '+': stack.append(num)
            if op == '-': stack.append(-num)
            if op == '*': stack.append(stack.pop() * num)
            if op == '/': stack.append(int(stack.pop() / num))
        
        # remove spaces
        s = s.replace(' ', '')
        
        stack = []
        num = 0
        pre_op = '+'
        for i in range(len(s)):
            if s[i].isdigit():
                num = 10 * num + int(s[i])
            elif s[i] in '+-*/':
                update(pre_op, num)
                num = 0
                pre_op = s[i]
        
        # last num
        update(pre_op, num)
        return sum(stack)

 

반응형
Comments