Leetcode - Basic Calculator II

Ji Kim·2020년 12월 28일
0

Algorithm

목록 보기
30/34

Leetcode : Basic Calculator II

Description

Given a string s which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero.

Example 1

Input

 s = "3+2*2"

Ouput

7

Example 2

Input

 s = " 3/2 "

Ouput

1

Example 3

Input

s = " 3+5 / 2 "

Ouput

5

Approach

When manipulating series of string in sequence, stack is an effective data-structure to apply. However, arithmetic sequence must be taken into account (i.e. - multiplication and division occur prior to addition and subtraction)

Solution (Python)

class Solution:
    def calculate(self, s: str) -> int:
        s = s.replace(" ", "")
        
        stack = []
        ops = ["+", "-", "*", "/"]
        
        op = "+"
        temp = 0 
        
        for i in range(len(s)):
            curr = s[i]
            
            if curr not in ops:
                temp = temp * 10 + int(curr)
            if curr in ops or i == len(s) - 1:
                if op == "+":
                    stack.append(temp)
                elif op == "-":
                    stack.append(-temp)
                elif op == "*":
                    temp = temp * stack.pop()
                    stack.append(temp)
                else:
                    div = stack.pop()
                    
                    if div > 0:
                        stack.append(div // temp)
                    else:
                        stack.append(-1 * (-div // temp))
            
                op = curr
                temp = 0 
                
        return sum(stack)

Result

Runtime : 84ms
Memory Usage : 15.7MB
Runtime Beats 69.08% of Python Submission

profile
if this then that

1개의 댓글

comment-user-thumbnail
2023년 7월 7일

I recently stumbled upon PerfectSink.com while searching for the perfect addition to my newly renovated kitchen, and I must say, I'm thoroughly impressed. From the moment I landed on their website, I knew I had found a gem in the world of kitchen sinks. browse this site check here original site my response pop over to these guys.

답글 달기