题目本身很简单,利用stack
即可,注意string
转换成int
->std::stoi(s)
,以及先判断是不是运算符,再判断是什么运算符,可以节省时间。
#include <stack>
#include <string>
#include <vector>
using std::stack;
using std::string;
using std::vector;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> stk;
int tmp1, tmp2;
for (string s : tokens) {
if (s == "/" || s == "+" || s == "*" || s == "-") {
if (s == "/") {
tmp1 = getTop(stk);
tmp2 = getTop(stk);
stk.push(tmp2 / tmp1);
} else if (s == "+") {
tmp1 = getTop(stk);
tmp2 = getTop(stk);
stk.push(tmp2 + tmp1);
} else if (s == "*") {
tmp1 = getTop(stk);
tmp2 = getTop(stk);
stk.push(tmp2 * tmp1);
} else if (s == "-") {
tmp1 = getTop(stk);
tmp2 = getTop(stk);
stk.push(tmp2 - tmp1);
}
} else {
int tmp = std::stoi(s);
stk.push(tmp);
}
}
return getTop(stk);
}
int getTop(stack<int> &st) {
int temp = st.top();
st.pop();
return temp;
}
};
标签:150,getTop,reverse,int,stk,push,求值,tmp1,tmp2
From: https://www.cnblogs.com/zwyyy456/p/16592801.html