Lintcode 逆波兰表达式求值
来源:互联网 发布:windows画图软件 编辑:程序博客网 时间:2024/05/17 08:14
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
您在真实的面试中是否遇到过这个题? Yes
样例
[“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 string_to_int(const string &string1) { int sym = 1; int num = 0; for (auto i : string1) { if (i == '-') { sym = 0; continue; } num = num * 10 + (i - '0'); } return sym == 0 ? -num : num; } int evalRPN(vector<string> tokens) { // write your code here stack<int> stack1; int temp = 0; int after = 0; for (auto s :tokens) { if (s == "+" || s == "-" || s == "*" || s == "/") { if (s == "+") { temp = after + stack1.top(); } else if (s == "-") { temp = after - stack1.top(); } else if (s == "*") { temp = after * stack1.top(); } else if (s == "/") { temp = after / stack1.top(); } stack1.pop(); stack1.pop(); if (!stack1.empty()) { after = stack1.top(); } stack1.push(temp); } else { if (!stack1.empty()) { after = stack1.top(); } stack1.push(string_to_int(s)); } } return stack1.top(); }};
阅读全文
0 0
- LintCode : 逆波兰表达式求值
- LintCode:逆波兰表达式求值
- Lintcode 逆波兰表达式求值
- lintcode--逆波兰表达式求值
- Lintcode 逆波兰表达式求值
- 逆波兰表达式求值-LintCode
- lintcode-逆波兰表达式求值-424
- LintCode 424-逆波兰表达式求值
- lintcode-逆波兰表达式求值-424
- LintCode:M-逆波兰表达式求值
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- KVO存在的坑
- Qt Creator:QSqlTableModel的进阶
- JavaWeb核心技术学习笔记(一)——网络编程基础
- 查看mysql索引具体方法
- Java 集合深入理解(13):Stack 栈
- Lintcode 逆波兰表达式求值
- C#基础之带表格的九九乘法
- protobuf定义低带宽的移动消息
- Python核心编程(第二版)第四章练习题
- u盘安装linux
- UNITY移动平台上的手势操作——旋转、缩放
- 微服务架构(spring-cloud)
- New Year and Rating CodeForces
- Java 集合深入理解(14):Map 概述