LeetCode: Evaluate Reverse Polish Notation [150]

來源:互聯網
上載者:User

標籤:leetcode   演算法   面試   

【題目】

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


【題意】

        計算用逆波蘭式表示的運算式的值


【思路】

        逆波蘭式其實是二叉樹的遍曆
        用棧求解即可,每次遇到運算子是計算棧頂的兩個元素
        
        注意:
            字串轉整數時,考慮負數的情況


【代碼】
class Solution {public:        int str2int(string token){        int num=0;        int start=0;        int isNev = 1;        //判斷符號        if(token[0]=='-'){isNev=-1; start++;}        else if(token[0]=='+')start++;        for(int i=start; i<token.length(); i++){            num=10*num+(token[i]-'0');        }        return num*isNev;    }        bool isOp(string token){        if(token=="/" || token=="+" || token=="-" || token=="*")            return true;    }        int evalRPN(vector<string> &tokens) {        stack<int> st;        for(int i=0; i<tokens.size(); i++){            if(isOp(tokens[i])){                //如果是運算子,則計算棧頂元素,然後將結果入棧                int val1 = st.top(); st.pop();                int val2 = st.top(); st.pop();                int res = 0;                if(tokens[i]=="+")  res = val2 + val1;                else if(tokens[i]=="-")  res = val2 - val1;                else if(tokens[i]=="*")  res = val2 * val1;                else if(tokens[i]=="/")  res = val2 / val1;                //計算結果入棧                st.push(res);            }            else{                //數字入棧                st.push(str2int(tokens[i]));            }        }        return st.top();    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.