水題一枚,直接壓棧出棧即可,不過調用內置函數可以節省很多力氣,如:
int stoi(const string& s);
具體代碼如下:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> s;
for(auto token:tokens){
if(is_digit(token))
s.push(stoi(token));
else{
int a = s.top();
s.pop();
int b = s.top();
s.pop();
switch(token[0]){
case '+':
b+=a; break;
case '-':
b-=a; break;
case '*':
b*=a; break;
case '/':
b/=a; break;
}
s.push(b);
}
}
return s.top();
}
private:
static bool is_digit(const string& token){
if((token.size()>1)||(token[0]>='0'&&token[0]<='9'))
return true;
return false;
}
};