標籤: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 };