天天看點

LintCode領扣 題解丨 BAT大廠面試高頻題:逆波蘭表達式求值

求逆波蘭表達式的值。

在逆波蘭表達法中,其有效的運算符号包括 +, -, *, / 。每個運算對象可以是整數,也可以是另一個逆波蘭計數表達。

線上評測位址:

https://www.lintcode.com/problem/evaluate-reverse-polish-notation/?utm_source=sc-tianchi-sz0814

樣例 1:

輸入: ["2", "1", "+", "3", "*"]

輸出: 9

解釋: ["2", "1", "+", "3", ""] -> (2 + 1) 3 -> 9

樣例 2:

輸入: ["4", "13", "5", "/", "+"]

輸出: 6

解釋: ["4", "13", "5", "/", "+"] -> 4 + 13 / 5 -> 6

【題解】

逆波蘭表達式是更利于計算機運算的表達式形式, 需要用到棧(先進後出的資料結構).

周遊表達式:

碰到數字則入棧

碰到運算符則連續從棧中取出2個元素, 使用該運算符運算然後将結果入棧

最後棧中剩餘一個數字, 就是結果.

public class Solution {

public int evalRPN(String[] tokens) {
    Stack<Integer> s = new Stack<Integer>();
    String operators = "+-*/";
    for (String token : tokens) {
        if (!operators.contains(token)) {
            s.push(Integer.valueOf(token));
            continue;
        }

        int a = s.pop();
        int b = s.pop();
        if (token.equals("+")) {
            s.push(b + a);
        } else if(token.equals("-")) {
            s.push(b - a);
        } else if(token.equals("*")) {
            s.push(b * a);
        } else {
            s.push(b / a);
        }
    }
    return s.pop();
}           

}

更多題解參見九章算法官網:

https://www.jiuzhang.com/solution/evaluate-reverse-polish-notation/?utm_source=sc-tianchi-sz0814

繼續閱讀