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

計(jì)算逆波蘭表達(dá)式的值,這個感覺比較簡單,就是利用一個棧,把數(shù)字都進(jìn)棧,然后碰到一個符號就出棧兩個數(shù)字,把結(jié)果進(jìn)棧,直到表達(dá)式結(jié)束或???。
就是這么簡陋的寫法,不過至少能AC是不

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int n = tokens.size();
        stack<int> s;
        for (int i=0; i<n; i++) {
            if (tokens[i] == "+") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x1 + x2);
            }
            else if (tokens[i] == "-") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x2 - x1);
            }
            else if (tokens[i] == "*") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x1 * x2);
            }
            else if (tokens[i] == "/") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                s.push(x2 / x1);
            }
            else {
                int x = stoi(tokens[i]);
                s.push(x);
            }
        }
        return s.top();
    }
};

有點(diǎn)長,寫的簡潔一點(diǎn)…

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int n = tokens.size();
        stack<int> s;
        for (int i=0; i<n; i++) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                int x1 = s.top();
                s.pop();
                int x2 = s.top();
                s.pop();
                if (tokens[i] == "+")
                    s.push(x1 + x2);
                else if (tokens[i] == "-")
                    s.push(x2 - x1);
                else if (tokens[i] == "*")
                    s.push(x1 * x2);
                else
                    s.push(x2 / x1);
            }
            else {
                int x = stoi(tokens[i]);
                s.push(x);
            }
        }
        return s.top();
    }
};

不過寫簡潔了,時間變長了一些,不過其實(shí)復(fù)雜度是一樣的是不。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容