LeetCode-150-Evaluate Reverse Polish Notation
发布时间:2020-12-14 21:50:34 所属栏目:大数据 来源:网络整理
导读:算法描述: Evaluate the value of an arithmetic expression in?Reverse Polish Notation. Valid operators are? + ,? - ,? * ,? / . Each operand may be an integer or another expression. Note: Division between two integers should truncate toward
算法描述: Evaluate the value of an arithmetic expression in?Reverse Polish Notation. Valid operators are? Note:
Example 1: Input: ["2","1","+","3","*"] Output: 9 Explanation: ((2 + 1) * 3) = 9 Example 2: Input: ["4","13","5","/","+"] Output: 6 Explanation: (4 + (13 / 5)) = 6 Example 3: Input: ["10","6","9","-11","*","17","+"] Output: 22 Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 = ((10 * (6 / (12 * -11))) + 17) + 5 = ((10 * (6 / -132)) + 17) + 5 = ((10 * 0) + 17) + 5 = (0 + 17) + 5 = 17 + 5 = 22 解题思路:逆波特兰表达式,用栈辅助模拟。 int evalRPN(vector<string>& tokens) { if(tokens.size()==0) return 0; stack<int> stk; for(auto c : tokens){ if(c == "+" || c == "-" || c== "*" || c=="/"){ int right = stk.top(); stk.pop(); int left = stk.top(); stk.pop(); int ans; if(c == "+") ans = left + right; if(c == "-") ans = left - right; if(c == "*") ans = left * right; if(c == "/") ans = left / right; stk.push(ans); }else{ stk.push(stoi(c)); } } return stk.top(); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |