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)) -> 6LeetCode Source
分析:很简单的利用堆栈来实现,当读入数字时放入栈,读入符号时出栈。
特别注意数字出栈的顺序。这个例子的Corner Case比较简单。
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> stk; for(int i=0;i<tokens.size();++i){ if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/") { //if(stk.size()<2){ // return 0; // } int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); if(tokens[i]=="+") stk.push(a+b); if(tokens[i]=="-") stk.push(a-b); if(tokens[i]=="/"){ // if(b==0) // return 0; // else stk.push(a/b); } if(tokens[i]=="*") stk.push(a*b); } else stk.push(stoi(tokens[i])); } //if(stk.size()!=1) // return 0; //else return stk.top(); } };