Leetcode 150 Evaluate Reverse Polish Notation 反向波兰表示法求值
2015-08-02 12:48
615 查看
原题地址
https://leetcode.com/problems/evaluate-reverse-polish-notation/题目描述
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
解题思路
反向波兰表示法的特点就是操作符在操作数的后面(后缀表示法),最后面的操作符是最后执行的运算,因此我们可以从前面开始往后计算,当遇到数字时,将其作为操作数压栈,当遇到操作符时,从操作数栈栈顶取出两个操作数来完成一次计算,并把计算结果存到操作数栈中,到最后操作数栈中只留下一个操作数就是计算结果算法描述
读取出下一个token,如果token不是操作符,则将其转换为相应的操作数压栈如果token是操作符,从栈中取出两个操作数来计算,将得到的值压入操作数栈中
到最后一个token处理结束时,操作数栈栈顶元素就是计算结果
代码 cpp
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> operands; vector<string>::iterator it = tokens.begin(), end = tokens.end(); int opA, opB; while (it != end) { if (*it == "+" || *it == "-" || *it == "*" || *it == "/") { opB = operands.top(); operands.pop(); opA = operands.top(); operands.pop(); operands.push(cal(opA, opB, *it)); } else { operands.push(valueOf(*it)); } ++it; } return operands.top(); } private: /** 字符串转换为相应数值 */ int valueOf(string str) { if (str == "") return 0; int symbol = 1, index = 0, len = str.size(), val = 0; if (str[0] == '+') { index = 1; } else if (str[0] == '-') { index = 1; symbol = -1; } for (; index < len; ++index) val = val * 10 + str[index] - '0'; return val * symbol; } /** 二元计算 */ int cal(int opA, int opB, string op) { int val = 0; switch (op[0]) { case '+': val = opA + opB; break; case '-': val = opA - opB; break; case '*': val = opA * opB; break; case '/': val = opA / opB; break; } return val; } };
完整代码https://github.com/Orange1991/leetcode/blob/master/150/cpp/main.cpp
运行情况
Language | Status | Time |
---|---|---|
cpp | Accept | 16ms |
相关文章推荐
- Lua面向对象
- lua - 表
- lua 库函数
- Lua基本语法
- lua 介绍
- UVA 1609 Foul Play 不公平竞赛 (构(luan)造(gao)+递归)
- [leedcode 150] Evaluate Reverse Polish Notation
- 【Lua】table
- 【Lua】pairs 和 ipairs
- 逆波兰表达式求值(Evaluate Reverse Polish Notation)
- 【Lua】loadfile、dofile、require详解
- 【转】Lua编程规范
- Lua基础
- Lua基础
- LUA中table和字符串相互转换
- Lua处理游戏数据
- LUA脚本调用C场景,使用C API访问脚本构造的表
- lua math lib
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- Lua 学习备忘录3