链接:逆波兰表达式求值_牛客题霸_牛客网
题解:
利用栈,遍历字符串数组,遇到运算数则入栈,遇到运算符则取出栈顶两个运算数进行运算,并将运算结果入栈。
class Solution {
public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param tokens string字符串vector * @return int整型*/int evalRPN(vector<string>& tokens) {// write code herestack<int> s;for(auto& c:tokens){if(c=="+"||c=="-"||c=="*"||c=="/"){int y=s.top();s.pop();int x=s.top();s.pop();int ret=0;if(c=="+") ret=x+y;else if(c=="-") ret=x-y;else if(c=="*") ret=x*y;else ret=x/y;s.push(ret);}else {s.push(stoi(c));}}return s.top();}
};