本文共 590 字,大约阅读时间需要 1 分钟。
Evaluate the value of an arithmetic expression in .
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&tokens) { if(tokens.size() == 0) return 0; string op[] = {"+", "-", "*", "/"}; stack mystack; map op_map; for (int i = 0; i
转载地址:http://ryxti.baihongyu.com/