March——224. Basic calculator I, II

class Solution:
    def calculate(self, s: str) -> int:
         # 初始化sign为 “+”,是因为开头是数字
        num ,stack ,sign = 0 , [] , '+'
        for i in range(len(s)):
            ch = s[i]
            if ch.isdigit():
                num = num * 10 + int(ch)
            #根据当前数字之前的符号,来决定如何处理当前数值
            # 并将处理后的数值压入栈中
            if ch in "+-*/" or i == len(s)-1:
                if sign == "+" :
                    stack.append(num)
                elif sign == "-" :
                    stack.append(-num)
                elif sign == "*":
                    stack.append(stack.pop() * num)
                else:
                    stack.append(int(stack.pop()/num))
                num = 0
                sign = ch
        return sum(stack)
  •  Topic analysis
    • From elementary school knowledge, we can understand that in basic calculations, first multiply and divide, then add and subtract. If there are parentheses, first calculate the value in the parentheses.
    • For this topic, there are no parentheses, so we first calculate multiplication and division, and then add and subtract
    • Basically, this problem needs to use the data structure of the stack to solve this problem. Initialize a stack and initialize a symbol. The initial symbols are all plus signs.
      • If it is a number, first calculate the string to an integer
      • If the current string is a character, then if it is addition and subtraction, multiply num by its coefficient, and then push it to the stack; if it is multiplication and division, first pop out the stack and perform operations on the current element, and then push it to the stack
      • Then update the current num to 0, and record the current coefficient
  • Summarize
    • One of the test points is how to convert a string into a decimal integer
    • Test center two, what should be done when encountering'+-*/'
    • Test point three, how to update the current coefficient and the next integer after each calculation

 

class Solution:
    def calculate(self, s: str) -> int:
        sDeque = deque(s)
        def helper(sDeque):
            num = 0
            sign = "+"
            stack = []
            while len(sDeque) > 0:
                # 注意 这里需要从头部开始pop
                char = sDeque.popleft()
                if char.isdigit():
                    num = num * 10 + int(char)
                if char == '(':
                    #遇到左括号,开始递归调用
                    num = helper(sDeque)                
                if (not char.isdigit() and char != " ") or len(sDeque) == 0:
                    if sign == "+":
                        stack.append(num)
                    elif sign == "-":
                        stack.append(-num)
                    elif sign =='*':
                        stack.append(stack.pop()*num)
                    elif sign == '/':
                        stack.append(stack.pop()/num)
                    # 重置num和sign
                    num = 0
                    sign = char
                if char == ")":
                    #遇到右括号直接结束当前的递归
                    break
            return sum(stack)
        return helper(sDeque)
  • Topic analysis
    • It is an upgraded version of the previous topic, with brackets added.
    • First convert the previous string into a deque
    • Others remain unchanged. If we encounter a left parenthesis, then we need to perform calculations recursively. If we encounter a right parenthesis to end this recursive call, just jump out of the while loop.

Here is a post on how to dismantle a complicated problem: to implement a calculator , labuladong is definitely a big man, and the explanation of this topic is very clear and clear.

Summary: I thought the stack was quite simple, but found that the simpler the data structure is really not so simple in the application of specific problems.

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/114680228