Leetcode 150:Evaluate Reverse Polish Notation
2015-05-02 15:57
603 查看
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:
分析:
此题是逆波兰式的四则混合运算问题,算法如下:
1、构建空栈S。
2、遍历集合中得元素,如果是操作符op,则从栈中弹出两个元素S1, S2,计算S2 op S1的结果。
如果是操作数,则将其压入到栈S中。
代码如下,运算时间大约84ms。
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
分析:
此题是逆波兰式的四则混合运算问题,算法如下:
1、构建空栈S。
2、遍历集合中得元素,如果是操作符op,则从栈中弹出两个元素S1, S2,计算S2 op S1的结果。
如果是操作数,则将其压入到栈S中。
代码如下,运算时间大约84ms。
class Solution { public: int evalRPN(vector<string> &tokens) { <span style="white-space:pre"> </span>if(tokens.size() == 0) return 0; string op[] = {"+", "-", "*", "/"}; stack<int> mystack; map<string, int> op_map; for (int i = 0; i<sizeof(op)/sizeof(op[0]); i++) { op_map[op[i]] = i; } for (int i =0; i<tokens.size(); i++) { string c = tokens[i]; if (op_map.count(c) != 0) { int num1 = mystack.top(); mystack.pop(); int num2 =mystack.top(); mystack.pop(); int num3; if (c == "+") { num3 = num1 + num2; } else if (c == "-") { num3 = num2 - num1; }else if (c == "*"){ num3 = num2 * num1; } else if(c == "/"){ num3 = num2 /num1; } mystack.push(num3); }else{ char *end; mystack.push(strtol(c.c_str(), &end, 10)); } } return mystack.top(); } };
相关文章推荐
- leetcode_c++:栈:Evaluate Reverse Polish Notation(150)
- LeetCode150—Evaluate Reverse Polish Notation
- Leetcode 150 Evaluate Reverse Polish Notation (求值逆波兰表达式)
- Leetcode#150 Evaluate Reverse Polish Notation
- LeetCode 150 Evaluate Reverse Polish Notation
- LeetCode 150 Evaluate Reverse Polish Notation
- Leetcode 150 Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- LeetCode: 150_Evaluate Reverse Polish Notation | 分析逆波兰式 | Medium
- LeetCode(150) Evaluate Reverse Polish Notation
- Java for LeetCode 150 Evaluate Reverse Polish Notation
- leetcode150 Evaluate Reverse Polish Notation
- leetcode 150: Evaluate Reverse Polish Notation
- [Leetcode 150, Medium] Evaluate Reverse Polish Notation
- [leetcode-150]Evaluate Reverse Polish Notation(c++)
- 【LeetCode】150 Evaluate Reverse Polish Notation 小侃小解
- leetcode150 Evaluate Reverse Polish Notation
- [leetcode 150] Evaluate Reverse Polish Notation
- 【LeetCode-面试算法经典-Java实现】【150-Evaluate Reverse Polish Notation(计算逆波兰式)】