LeetCode OJ——練習筆記(1)Evaluate Reverse Polish Notation

來源:互聯網
上載者:User

標籤:style   blog   http   color   資料   for   

院招終於開始了,然後期待與興奮過後卻是面臨著筆試一次又一次的失敗,然後開始留意到LeetCode。

也想自己去體驗一下諸多大牛通向無限coding路上都攻克過的一關。

話不多說,貼出原題:

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

該題知識點用到了資料結構中學過的逆波蘭運算式,思路就是:藉助棧,遇數字則入棧,遇運算元則取棧頂兩個字元出棧,返回運算結果再入棧,到最後棧裡剩下的唯一數字就是結果,
稍微注意一下可能出現的只有一個數位這種情況,還有就是先出棧的作為運算元2,後出棧的作為操作符1,這在減法和除法中可能會出錯。
 1 class Solution { 2 public: 3     int evalRPN(vector<string> &tokens) { 4          stack<int> stk; 5         for(int i=0;i<tokens.size();i++){ 6             if(tokens[i].length()==1 && (tokens[i][0]>‘9‘ || tokens[i][0]<‘0‘)) 7             { 8                 int o2 = stk.top(); 9                 stk.pop();10                 int o1 = stk.top();11                 stk.pop();12                 switch(tokens[i][0])13                 {14                     case ‘+‘: stk.push(o1+o2); break;15                     case ‘-‘: stk.push(o1-o2); break;16                     case ‘*‘: stk.push(o1*o2); break;17                     case ‘/‘: stk.push(o1/o2); break;18                 }19             }20             else21                 stk.push(atoi(tokens[i].c_str()));22         }23         return stk.top();24     }25 };

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.