LintCode_424_逆波兰表达式求值
2017-08-22 19:07
537 查看
问题描述
求逆波兰表达式的值。在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
样例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
求解
class Solution { public: /* * @param tokens: The Reverse Polish Notation * @return: the value */ int evalRPN(vector<string> tokens) { if (tokens.empty()) { return 0; } stack<int> s; auto is_operator = [](const string &op) -> bool { return op.length() == 1 && string("+-*/").find(op) != string::npos; }; for (const auto& tok : tokens) { if (!is_operator(tok)) { s.emplace(stoi(tok)); } else { int y = s.top(); s.pop(); int x = s.top(); s.pop(); if (tok[0] == '+') { x += y; } else if (tok[0] == '-') { x -= y; } else if (tok[0] == '*') { x *= y; } else { x /= y; } s.emplace(x); } } return s.top(); } };
相关文章推荐
- LintCode 424-逆波兰表达式求值
- lintcode-424-逆波兰表达式求值
- LintCode_424_逆波兰表达式求值
- lintcode-逆波兰表达式求值-424
- lintcode 中等题:Evaluate Reverse Polish notation逆波兰表达式求值
- 逆波兰表达式求值-LintCode
- LintCode : 逆波兰表达式求值
- lintcode-逆波兰表达式求值-424
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- Lintcode 逆波兰表达式求值
- LintCode:M-逆波兰表达式求值
- lintcode--逆波兰表达式求值
- Lintcode 逆波兰表达式求值
- [数据结构]从中序表达式到逆序表达式(逆波兰式)(四则运算表达式求值)
- 【算法】表达式求值--逆波兰算法介绍
- LintCode 将表达式转换为逆波兰式
- 逆波兰表达式求值
- 从中序表达式到逆序表达式(逆波兰式)(四则运算表达式求值)
- 河南省第九届acm省赛 A:表达式求值 逆波兰表达式
- 中缀表达式转换成后缀表达式以及逆波兰表示法求值