当前位置: 代码迷 >> 综合 >> [LeetCode] Evaluate Reverse Polish Notation | 逆波兰表达式求值
  详细解决方案

[LeetCode] Evaluate Reverse Polish Notation | 逆波兰表达式求值

热度:17   发布时间:2023-12-22 05:38:51.0

https://leetcode.com/problems/evaluate-reverse-polish-notation/?tab=Description

开一个栈,遇到数字压栈,遇到运算符就从栈中弹出两个元素做相应的计算然后再压回去。

Time complexity: O(n)
Space complexity: O(n)

class Solution { public:int evalRPN(vector<string>& tokens) {if (tokens.empty()) return 0;if (tokens.size() == 1) return stoi(tokens[0]);stack<int> stk;int ret = 0;for (int i = 0; i < tokens.size(); ++i) {string& str = tokens[i];if (isop(str)) {int x = stk.top(); stk.pop();int y = stk.top(); stk.pop();if (str == "+") {ret = y + x;} else if (str == "-") {ret = y - x;} else if (str == "*") {ret = y * x;} else {ret = y / x;}stk.push(ret);} else {stk.push(stoi(str));}}return ret;} private:bool isop(string& str) {return (str == "+" || str == "-" || str == "*" || str == "/");} };

转载于:https://www.cnblogs.com/ilovezyg/p/6435646.html

  相关解决方案