Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is +
, -
, *
, /
. Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
Hide TagsStack The topic is to maintain a formula with stack in and out, judging method can also, start to forget the number may be negative, the latter improved.
#include <stack>#include<iostream>#include<string>#include<vector>using namespacestd;classSolution { Public: intEVALRPN (vector<string> &tokens) { intn =tokens.size (); Stack<int>tmp; for(intI=0; i<n;i++){ if(tokens[i][0]>='0'&&tokens[i][0]<='9') {Tmp.push (Helpfun (tokens[i)); Continue; } if(tokens[i][0]=='-'&&tokens[i][1]!=' /') {Tmp.push (Helpfun (tokens[i)); Continue; } intRGT =Tmp.top (); Tmp.pop (); intLFT =Tmp.top (); Tmp.pop (); Switch(tokens[i][0]){ Case '+': Tmp.push (LfT+RGT); Break; Case '-': Tmp.push (LfT-RGT); Break; Case '*': Tmp.push (LfT*RGT); Break; Case '/': Tmp.push (LfT/RGT); Break; } } returnTmp.top (); } intHelpfun (stringstr) { intsum =0, i =0; if(str[0]=='-') I=1; for(; I<str.length (); i++) Sum= sum*Ten+str[i]-'0'; returnstr[0]=='-'?-sum:sum; }};intmain () {vector<string> tokens{"3","-4","+"}; Solution Sol; cout<<SOL.EVALRPN (Tokens) <<Endl;//for (int i=0;i<tokens.size (); i++)//cout<<tokens[i]<<endl; return 0;}
[Leetcode] Evaluate Reverse Polish Notation Stack stack