Evaluate Reverse Polish Notation
2014.2.25 23:42
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Solution:
The Reverse Polish Notation is a postorder traversal of the syntax tree, which is constructed with operands and operators.
With a stack it would be easy to process the sequence and calculate the result.
Total time and space complexities are both O(n).
Accepted code:
1 // 1AC, simple training on stack operation. 2 #include <stack> 3 #include <vector> 4 using namespace std; 5 6 class Solution { 7 public: 8 int evalRPN(vector<string> &tokens) { 9 int i, n; 10 int op1, op2; 11 stack<int> nums; 12 bool is_op; 13 14 n = (int)tokens.size(); 15 for (i = 0; i < n; ++i) { 16 is_op = false; 17 if (tokens[i].length() == 1) { 18 switch(tokens[i][0]) { 19 case '+': 20 case '-': 21 case '*': 22 case '/': 23 is_op = true; 24 break; 25 } 26 } 27 28 if (is_op) { 29 if (nums.size() < 2) { 30 // not enough operands 31 return 0; 32 } 33 op2 = nums.top(); 34 nums.pop(); 35 op1 = nums.top(); 36 nums.pop(); 37 switch (tokens[i][0]) { 38 case '+': 39 nums.push(op1 + op2); 40 break; 41 case '-': 42 nums.push(op1 - op2); 43 break; 44 case '*': 45 nums.push(op1 * op2); 46 break; 47 case '/': 48 if (op2 == 0) { 49 // divide by 0 50 return 0; 51 } 52 nums.push(op1 / op2); 53 break; 54 } 55 } else { 56 if (sscanf(tokens[i].c_str(), "%d", &op1) != 1) { 57 // invalid integer format 58 return 0; 59 } 60 nums.push(op1); 61 } 62 } 63 int result = nums.top(); 64 nums.pop(); 65 66 return result; 67 } 68 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)