时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M 热度指数:107386
题目描述
计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
例如:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵ ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
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
class Solution {
public:
int s2i(string s){
int len=s.size();
int sum=0;
int i=0;
//还要注意负数的情况
if(s[0]=='-')i=1;
for(;i<len;i++){
sum=sum*10+(s[i]-'0');
}
if(s[0]=='-')sum=-sum;
return sum;
}
int evalRPN(vector<string> &tokens) {
//注意定义的是栈,不是队列(栈顶是top,队首是front)
stack<int>q;
for(int i=0;i<tokens.size();i++){
if(tokens[i].size()==1&&(tokens[i][0]=='+'||tokens[i][0]=='-'||tokens[i][0]=='*'||tokens[i][0]=='/')){
int b=q.top();
q.pop();
int a=q.top();
q.pop();
if(tokens[i][0]=='+'){
q.push(a+b);
}
else if(tokens[i][0]=='-'){
q.push(a-b);
}
else if(tokens[i][0]=='*'){
q.push(a*b);
}
else if(tokens[i][0]=='/'){
q.push(a/b);
}
}
else{
q.push(s2i(tokens[i]));
}
}
return q.top();
}
};