这道题主要难点是栈(stack)的使用。
#include <iostream>
#include <string.h>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
bool IsOp(string s)
{
if (s == "+" || s == "-" || s == "*" || s == "/")
return true;
else return false;
}
int evalRPN(vector<string> &tokens) {
vector<string>::iterator it;
stack<int> s;
int result = 0;
for (it = tokens.begin(); it != tokens.end(); it++)
{
int a;
if (!IsOp(*it))
{
a = atoi((*it).data());
s.push(a);
}
else
{
char op = (*it).data()[0];
int a = s.top(); s.pop();
int b = s.top(); s.pop();
switch (op)
{
case '+':result = b + a; break;
case '-':result = b - a; break;
case '*':result = b * a; break;
case '/':result = b / a; break;
default:
break;
}
s.push(result);
}
}
return s.top();
}
};