class Solution
{
private:
stack<int> s; //利用栈来求解
public:
int evalRPN(vector<string>& tokens)
{
for (auto t : tokens) //利用范围for遍历整个容器
{
if (t != "+" && t != "-" && t != "*" && t != "/") //这里判断一下是不是+-*/运算符
{
string temp = t; //如果不是+-*/运算符那一定是数字
s.push(atoi(temp.c_str())); //但因为题目中给出的是string,所以要转换成int再进栈
}
else //这里说明的确是+-*/运算符,所以我们取出栈中前两个元素进行运算
{
int a = s.top();
s.pop();
int b = s.top();
s.pop();
if (t == "+")
{
s.push(b + a);
}
else if (t == "-")
{
s.push(b - a); //一定要注意运算顺序,因为栈是“后进先出”,运算后的结果别忘了进栈
}
else if (t == "*")
{
s.push(b * a);
}
else if (t == "/")
{
s.push(b / a);
}
}
}
return s.top(); //最后栈中剩下的最后一个元素就是结果
}
};
150. 逆波兰表达式求值
最新推荐文章于 2024-08-03 20:10:04 发布