LeetCode 150:逆波蘭表達式求值 Evaluate Reverse Polish Notation

題目:

根據逆波蘭表示法,求表達式的值。java

有效的運算符包括 +, -, *, / 。每一個運算對象能夠是整數,也能夠是另外一個逆波蘭表達式。python

Evaluate the value of an arithmetic expression in Reverse Polish Notation.express

Valid operators are +, -, *, /. Each operand may be an integer or another expression.數組

說明:數據結構

  • 整數除法只保留整數部分。
  • 給定逆波蘭表達式老是有效的。換句話說,表達式總會得出有效數值且不存在除數爲 0 的狀況。

Note:app

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

示例 1:ide

輸入: ["2", "1", "+", "3", "*"]
輸出: 9
解釋: ((2 + 1) * 3) = 9

示例 2:函數

輸入: ["4", "13", "5", "/", "+"]
輸出: 6
解釋: (4 + (13 / 5)) = 6

示例 3:lua

輸入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
輸出: 22
解釋: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

擴展:

逆波蘭表達式,它的語法規定,表達式必須以逆波蘭表達式的方式給出。逆波蘭表達式又叫作後綴表達式。這個知識點在數據結構和編譯原理這兩門課程中都有介紹,下面是一些例子:指針

a+b ---> a,b,+
a+(b-c) ---> a,b,c,-,+
a+(b-c)*d ---> a,b,c,-,d,*,+
a+d*(b-c)--->a,d,b,c,-,*,+
a=1+3 ---> a,1,3,+,=

從上面的例子能夠看出: (1) 在兩種表示中,運算對象出現的順序相同; (2) 在後綴表示中,運算符按實際計算順序從左到右排列,且每一運算符老是跟在其運算對象以後。

<!--來自百度百科-->

這種表達式很反人類,可是對計算機很友好,由於計算機運算是利用棧數據結構。

解題思路:

能夠看出逆波蘭表達式中的每個運算符屬於該運算符前的兩個數字間的運算。如:

如波蘭表達式:1,2,+
則加號前兩個數字爲1,2。其運算符就是加號:1+2
得出結果:1+2=3

如波蘭表達式:1,2,3,+,-
則加號前兩個數字爲2,3。其運算符就是加號:2+3
得出結果2+3=5,則波蘭表達式變爲:1,5,-
減號前兩個數字爲1,5,其運算符就是減號:1-5
得出結果1-5=-4

由上面的的例子思路就很清晰了,直接用指針遍歷表達式,遇到數字就入棧,遇到運算符就彈出兩個數字,把他們運算以後得出結果,再做爲獨立數字入棧。最後棧內只剩一個元素 即表達式運算結果。也能夠用遞歸

Java:

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String t : tokens) {
            if (t.equals("+")) {
                stack.push(stack.pop() + stack.pop());
            } else if (t.equals("-")) {
                int tmp = stack.pop();
                stack.push(stack.pop() - tmp);
            } else if (t.equals("*")) {
                int tmp = stack.pop();
                stack.push(stack.pop() * tmp);
            } else if (t.equals("/")) {
                int tmp = stack.pop();
                stack.push(stack.pop() / tmp);
            } else {
                stack.push(Integer.parseInt(t));
            }
        }
        return stack.pop();
    }
}

Python:

python也能夠用數組代替棧完成上述方法解答本題。這裏用另外一個函數 eval() 代替上述四個 if 判斷:

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for t in tokens:
            if t in '+-*/':
                tmp = stack.pop()
                stack.append(int(eval('stack.pop()' + t + 'tmp')))
            else:
                stack.append(int(t))
        return stack.pop()

eval() 函數能夠執行傳入參數 字符串語句。

eval('print("hhhhh")') 會執行參數字符串打印出hhhhh

歡迎你們關注微.信公.衆號:愛寫Bug 在這裏插入圖片描述

相關文章
相關標籤/搜索