LeetCode——Evaluate Reverse Polish Notation
来源:互联网 发布:linux检查文件是否存在 编辑:程序博客网 时间:2024/05/29 14:56
题目:
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
解答:
class Solution {public: int calcWithOperator(const string& op, int l, int r) { char c = *op.c_str(); switch (c) { case '+': return l + r; case '-': return l - r; case '*': return l * r; case '/': return l / r; } return 0; } bool isStringOperator(const string& str) { if (str.length() != 1) { return false; } char c = *str.c_str(); return c == '+' || c == '-' || c == '*' || c == '/'; } int evalRPN(vector<string>& tokens) { stack<int> stackNum; for (int i = 0; i != tokens.size(); ++i) { const string str = tokens[i]; if (isStringOperator(str)) { if (stackNum.size() < 2) { return -1; } else { int r = stackNum.top(); stackNum.pop(); int l = stackNum.top(); stackNum.pop(); int result = calcWithOperator(str, l, r); stackNum.push(result); } } else { stackNum.push(atoi(str.c_str())); } } if (stackNum.size() != 1) { return -1; } else { return stackNum.top(); } }};
0 0
- LeetCode——Evaluate Reverse Polish Notation
- LeetCode——Evaluate Reverse Polish Notation
- leetcode 150 —— Evaluate Reverse Polish Notation
- LeetCode题解——Evaluate Reverse Polish Notation
- LeetCode—Evaluate Reverse Polish Notation解题报告
- LeetCode 之 Evaluate Reverse Polish Notation — C++ 实现
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- 分析Reporting Service的报表执行记录
- Android 四大组件之Content Provider
- emlog 如何插入百度统计代码
- Python笔记:multiprocessing模块详解
- 【C++基础】——const关键字
- LeetCode——Evaluate Reverse Polish Notation
- mysql学习笔记(一)
- IOS 屏幕尺寸、分辨率、点之间的相互关系
- java版排序算法简介及冒泡排序以及优化,选择排序,直接插入排序,希尔排序,堆排序,快速排序及其优化前言2 分类2 稳定性3 时间复杂度4 Java实现版本5 1、冒泡排序6 2、选择排序
- Rust中文翻译16
- linux sed命令
- Adaptive Layout Tutorial: Getting Started
- ios8新特性屏幕适配之sizeclass
- Java Scanner next()和nextLine()的区别