栈
- 思路:
- 使用栈存放运算数;
- 遍历 tokens,当遇到运算符时,2 次出栈得到运算数进行相应的运算,将运算结果入栈;
- 最终的结果在栈顶上;
class Solution {
public:int evalRPN(vector<string>& tokens) {std::stack<int> stk;int size = tokens.size();for (int idx = 0; idx < size; ++idx) {std::string token = tokens[idx];if (isNumber(token)) {stk.push(atoi(token.c_str()));} else {int num2 = stk.top();stk.pop();int num1 = stk.top();stk.pop();switch (token[0]) {case '+':stk.push(num1 + num2);break;case '-':stk.push(num1 - num2);break;case '*':stk.push(num1 * num2);break;case '/':stk.push(num1 / num2);break;}}}return stk.top();}private:bool isNumber(const std::string& s) {return !((s == "+") || (s == "-") || (s == "*") || (s == "/"));}
};