Leetcode Problem Solving evaluate Reverse Polish notation original problem
Computes the suffix form of the expression (also known as the inverse Polish expression) and returns the result. The operator is only subtraction four, and the operand is an integer or an expression.
Note the point:
Example:
Input: Tokens = ["2", "1", "+", "3", "*"]
Output: 9
Thinking of solving problems
The suffix expression is in the form of a 操作数1,操作数2,操作符
two number (or expression) of the operator to perform the calculation operation in front of it, so in the traversal of the list, we have to press the previous operator into the stack, when the operator is encountered, we have its corresponding operand popped and calculated, The result of the calculation may be the operands of other operators, it is an expression, we calculate the value of the expression, so we should continue to press that value stack, the end of the entire list, the calculation is finished. It is particularly important to note that the division operation, because the given expression is legal, so do not consider the divisor is zero, but here the division operation is for integers, the result will be the tail operation. The division operation for negative numbers and integers is also different from Python's own calculation, and Python evaluates -1//2
to-1, which should be 0 here, so special handling is needed.
AC Source
class solution(object): def evalrpn(self, Tokens): "" : Type Tokens:list[str]: Rtype:int " " "stack = [] forTokeninchTokensifToken not inch("+","-","*","/"): stack.append (int (token))Else: Second = Stack.pop () First = Stack.pop ()iftoken = ="+": Stack.append (first + second)eliftoken = ="-": Stack.append (First-second)eliftoken = =' * ': Stack.append (First * second)Else:ifFirst * Second <0: Stack.append (-(ABS (first)//ABS (second)))Else: Stack.append (First//second)returnStack.pop ()if__name__ = ="__main__":assertSolution (). EVALRPN (["2","1","+","3","*"]) ==9 assertSolution (). EVALRPN (["4","very","5","/","+"]) ==6 assertSolution (). EVALRPN (["Ten","6","9","3","+"," -11","*","/","*"," the","+","5","+"]) == A
Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.
Leetcode Evaluate Reverse Polish Notation