Leetcode 150 Evaluate Reverse Polish Notation 反向波蘭表示法求值

原題地址

https://leetcode.com/problems/evaluate-reverse-polish-notation/

題目描述

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
求解使用反向波蘭表示法描述的一個算術表達式的值。

Valid operators are +, -, *, /. Each operand may be an integer or another expression.
合法的運算符有+,-,*,/。操作數是整數或者另一個表達式。

Some examples:
一些例子:

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

解題思路

反向波蘭表示法的特點就是操作符在操作數的後面(後綴表示法),最後面的操作符是最後執行的運算,因此我們可以從前面開始往後計算,當遇到數字時,將其作爲操作數壓棧,當遇到操作符時,從操作數棧棧頂取出兩個操作數來完成一次計算,並把計算結果存到操作數棧中,到最後操作數棧中只留下一個操作數就是計算結果

算法描述

  1. 讀取出下一個token,如果token不是操作符,則將其轉換爲相應的操作數壓棧
  2. 如果token是操作符,從棧中取出兩個操作數來計算,將得到的值壓入操作數棧中
  3. 到最後一個token處理結束時,操作數棧棧頂元素就是計算結果

代碼 cpp

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> operands;
        vector<string>::iterator it = tokens.begin(), end = tokens.end();
        int opA, opB;

        while (it != end) {
            if (*it == "+" || *it == "-" || *it == "*" || *it == "/") {
                opB = operands.top();
                operands.pop();
                opA = operands.top();
                operands.pop();
                operands.push(cal(opA, opB, *it));
            } else {
                operands.push(valueOf(*it)); 
            }
            ++it;
        }

        return operands.top();       
    }

private:
    /** 字符串轉換爲相應數值 */
    int valueOf(string str) {
        if (str == "") return 0;
        int symbol = 1, index = 0, len = str.size(), val = 0;
        if (str[0] == '+') {
            index = 1;
        } else if (str[0] == '-') {
            index = 1;
            symbol = -1;
        }
        for (; index < len; ++index)
            val = val * 10 + str[index] - '0';
        return val * symbol;
    }

    /** 二元計算 */
    int cal(int opA, int opB, string op) {
        int val = 0;
        switch (op[0]) {
            case '+': val = opA + opB; break;
            case '-': val = opA - opB; break;
            case '*': val = opA * opB; break;
            case '/': val = opA / opB; break;
        }
        return val;
    }
};

完整代碼https://github.com/Orange1991/leetcode/blob/master/150/cpp/main.cpp

運行情況

Language Status Time
cpp Accept 16ms

2015/8/2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章