Likou brushing notes: 224. Basic calculator (using the stack to process the priority of parentheses, mainly because the logic should be clear, the code is commented line by line, and the little cousin can understand it)

topic:

224. Basic calculator
Implement a basic calculator to calculate the value of a simple string expression s.

Example 1:

Input: s = "1 + 1"
Output: 2

Example 2:

Input: s = "2-1 + 2"
Output: 3

Example 3:

Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23

prompt:

1 <= s.length <= 3 * 10^5
s is composed of numbers,'+','-','(',')', and ''
s represents a valid expression

Problem solution ideas:

Focus:

This question only has "+", "-" operations, no "*", "/" operations, so there is no comparison of the precedence of different operators;
when you encounter parentheses, you should count the expressions in the parentheses first;

Recursion
An expression is divided into three parts:

Left expression ①, operator ③, right expression ②

In this question, the expression on the left and right can be a number or an expression enclosed in parentheses; the operator can be addition and subtraction.

Elementary school mathematics tells us that an expression that only contains addition, subtraction and parentheses, we can calculate from left to right, and when we encounter parentheses, we count the inside of the parentheses first. Specifically, first calculate the expression on the left, then calculate the expression on the right, and finally calculate the operations of ① and ② according to the operator.

Use the title example "(1+(4+5+2)-3)+(6+8)" to illustrate the order of operator calculation:
Insert picture description here
According to the above analysis, we can see that when we are calculating an expression, we need to first Calculate the left expression ①, and then need to save the result of ① and the operator ③, then need to calculate the right expression ②, and finally calculate the operations of ① and ②. This operation is recursion! !

The stack
recursive program can be simulated with a "stack": in order to save the calculation result of the expression ① on the left and the operator ③, after calculating the result of the expression ③ on the right, the results of the operators ③ and ① are taken out of the stack, and then Perform the calculation of the result of the entire expression.

There must be a friend who wants to ask, if you use the stack to save the result of the expression on the left, what should you do when you encounter nested parentheses? For example (1 + (2 + (3 + 4))).
The answer is: the top of the stack retains the innermost nested operations. When the stack is popped, the innermost parentheses are counted first, and then the outer parentheses are counted. In this case, what is stored in the stack is ["1", "+", "2", "+", "3", "+"], then 4 is encountered, and the calculation is 3 + 4, Then count 7 + 2, then count 9 + 1. You can use recursion to help understand.

See code comments for specific operations.

Problem solution python code:

class Solution:
    def calculate(self, s: str) -> int:
        res, num, sign = 0, 0, 1
        stack = []
        for c in s:
            if c.isdigit():
                num = num*10+int(c)  # 应付部分两位数的数字
            elif c=="+" or c=="-":
                res += num*sign  # 遇到加减号就更新res和sign,然后重置num
                sign = 1 if c=="+" else -1
                num = 0
            elif c=="(":
                stack.append(res)  # 遇到左括号先保存临时结果
                stack.append(sign)   # 再保存符号,等右括号出现拿出
                res, sign = 0, 1   # 重置res、sign保存括号内的结果
            elif c==")":
                res += num*sign   # 利用num更新括号内res,然后重置num
                num = 0
                res *= stack.pop()   # 遇到右括号先取出sign更新括号内的res
                res += stack.pop()   # 再加上之前的栈内res
        res += num*sign   # 最后加上末尾的数字
        return res

Insert picture description here

Author: fuxuemingzhu
link: https://leetcode-cn.com/problems/basic-calculator/solution/ru-he-xiang-dao-yong-zhan-si-lu-lai-zi-y-gpca/
Source: force Deduction (LeetCode) https://leetcode-cn.com/problems/basic-calculator/
—————————————————————————————— --------------
author: a-qing-ge
Links: https://leetcode-cn.com/problems/basic-calculator/solution/li-yong-zhan-lai-chu -li-gua-hao-you-xian-6hsa/
Source: LeetCode https://leetcode-cn.com/problems/basic-calculator/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114629770