1. 整體思路,定義數據棧存放數據, 只要遇到運算符就出棧兩個數做加減乘除處理.
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(int i=0;i<tokens.size();i++) {
if(tokens[i]!="+" && tokens[i]!="-" && tokens[i]!="*" && tokens[i]!="/") {
int num = stoi(tokens[i]);
st.push(num);
}
else {
int second = st.top(); st.pop();
int first = st.top(); st.pop();
int all = 0;
if(tokens[i]=="+") all = first+second;
if(tokens[i]=="-") all = first-second;
if(tokens[i]=="*") all = first*second;
if(tokens[i]=="/") all = first/second;
st.push(all);
}
}
return st.top();
}
};