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
这是一道极为简单的入门级题目,考察的是对于栈的理解。当然,如果用STL的话,连理解也不用了。直接搞定。
唯一值得注意的是不要低级的造轮子。C标准库里面有的函数,就不要再自己写了,否则只是出力不讨好而已。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int i1 = 0, i2 = 0;
for(auto tempStr : tokens)
{
if (isdigit(tempStr[0]) || tempStr.size()>1)
{
s.push(atoi(tempStr.c_str()));
continue;
}
switch(tempStr[0]){
case '+':
i1 = s.top(); s.pop();
i2 = s.top(); s.pop();
i2 += i1;
s.push(i2);
break;
case '-':
i1 = s.top(); s.pop();
i2 = s.top(); s.pop();
i2 -= i1;
s.push(i2);
break;
case '*':
i1 = s.top(); s.pop();
i2 = s.top(); s.pop();
i2 *= i1;
s.push(i2);
break;
case '/':
i1 = s.top(); s.pop();
i2 = s.top(); s.pop();
i2 /= i1;
s.push(i2);
break;
}
}
i2 = s.top();
return i2;
}
private:
std::stack<int> s;
};
可以看出,使用了标准C库 <cctype>中的 int isdigit(int c) 函数,如果c是数字字符,返回非0值,否则,返回0. 还使用了int atoi (const char * str); 函数,从名字可以看出,把C字符串风格的数字字符转换为数字。