我的代码,在VS上能运行,在牛客上显示程序段错误;
int evalRPN(vector<string> &tokens)
{
if (tokens.size() == 0)
return 0;
int sum = 0;
stack <int> stk;
for (int i = 0; i < tokens.size(); i++)
{
for (int j = 0; j < tokens[i].length(); j++)
{
if ((tokens[i][j]) >= '0' && tokens[i][j] <= '9')
stk.push(tokens[i][j]-48);
else if (tokens[i][j] == '+')
{
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s1 + s2;
stk.push(sum);
}
else if (tokens[i][j] == '-')
{
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s2 - s1;
stk.push(sum);
}
else if (tokens[i][j] == '*')
{
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s1*s2;
stk.push(sum);
}
else if (tokens[i][j] == '/')
{
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s2 / s1;
stk.push(sum);
}
}
}
return sum;
}
正确的代码:
int evalRPN(vector<string> &tokens) {
int sum = 0;
stack <int> stk;
for (auto token:tokens) //遍历tokens中的每个元素
{
if (token == "+")
{
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s1 + s2;
stk.push(sum);
}
else if (token== "-")
{
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s2 - s1;//因为之前的结果先入栈,所以其后出栈;
stk.push(sum);
}
else if (token == "*")
{
if(stk.size()<2)
return 0;
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s1*s2;
stk.push(sum);
}
else if (token == "/")
{
if(stk.size()<2)
return 0;
int s1 = stk.top();
stk.pop();
int s2 = stk.top();
stk.pop();
sum = s2 / s1;
stk.push(sum);
}
else
{
stk.push(atoi(token.c_str()));//c_str()是将string类型的字符串转换成char *类型的字符串;
// atoi(char *) 是将字符串转换成整数值,所以就把token从string 转换成了int;
}
}
return stk.top();//栈顶元素即使最后的结果;
}