时间限制:1秒 空间限制:32768K
题目描述
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 evalRPN(vector<string> &tokens) {
int s_size=tokens.size();
if(s_size<1) return -1000000;
stack<int> st;
int st_size;
for(int i=0;i<s_size;i++){
if(tokens[i]=="+" or tokens[i]=="-" or
tokens[i]=="*" or tokens[i]=="/"){
st_size=st.size();
if(st_size<2)
return -1000000;
int op2=st.top();
st.pop();
int op1=st.top();
st.pop();
int res;
if(tokens[i]=="+")
res=op1+op2;
else if (tokens[i]=="-")
res=op1-op2;
else if(tokens[i]=="*")
res=op1*op2;
else{
if(op2==0)
return -1000000;
res=op1/op2;
}
st.push(res);
}
else{
st.push(stoi(tokens[i]));
//st.push(atoi(tokens[i].c_str()));
//stringstream ss;
//ss<<tokens[i];
//int tmp;ss>>tmp;
//st.push(tmp);
}
}
int res=st.top();
st.pop();
if(!st.empty())
return -1000000;
return res;
}
};
运行时间:5ms
占用内存:584k
网友评论