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

思路:

题目的意思是表达式总是先给出两个操作数,然后再给出对应的操作符。当给出一个这样的表达式后,求出表达式对应的值。

难点是后面操作符的操作数也是表达式。解决方法是用一个栈nums来保存所有没有用过的操作数,当遇到操作符时,栈最上面的两个数字就是操作符对应的操作数。最先遇到的操作符他的操作数一定没有嵌套表达式,所以可以得到值,当运算得到新的数字后,压入栈,作为下一个操作符的操作数。

我的代码:数字与字符串转换的时候比较丑。

int evalRPN2(vector<string>& tokens)
{
if(tokens.size() == )
return atoi(tokens[].c_str());
vector<string> nums;
for(int i = ; i < tokens.size(); i++)
{
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
string sPreNum, sPostNum, sOp;
int preNum, postNum, tmp;
sPostNum = nums.back();
nums.pop_back();
sPreNum = nums.back();
nums.pop_back();
preNum = atoi(sPreNum.c_str());
postNum = atoi(sPostNum.c_str());
sOp = tokens[i];
switch(sOp[])
{
case '+':
tmp = preNum + postNum; break;
case '-':
tmp = preNum - postNum; break;
case '*':
tmp = preNum * postNum; break;
case '/':
tmp = preNum / postNum; break;
default:
break;
}
char ctmp[];
sprintf(ctmp, "%d", tmp);
nums.push_back(ctmp);
}
else
{
nums.push_back(tokens[i]);
}
}
return atoi(nums[].c_str());
}

大神用递归的答案,相对短一些,但是逻辑不好理解。

int eval_expression(vector<string>& tokens, int& pt)
{
string s = tokens[pt]; if(s == "+" || s == "-" || s == "*" || s== "/") // tokens[r] is an operator
{
pt--;
int v2 = eval_expression(tokens, pt);
pt--;
int v1 = eval_expression(tokens, pt);
if(s == "+")
return v1 + v2;
else if(s == "-")
return v1 - v2;
else if(s == "*")
return v1 * v2;
else
return v1 / v2;
}
else // tokens[r] is a number
{
return atoi(s.c_str());
}
} int evalRPN(vector<string> &tokens) {
int pt = tokens.size()-;
return eval_expression(tokens, pt);
}

【leetcode】Evaluate Reverse Polish Notation(middle)的更多相关文章

  1. 【leetcode】Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation 题目描述: Evaluate the value of an arithmetic expression in Reverse Pol ...

  2. 【Leetcode】Evaluate Reverse Polish Notation JAVA

       一.问题描述 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators ...

  3. Leetcode 之Evaluate Reverse Polish Notation(41)

    很简单的一道题,定义一个栈保留操作数,遇操作符则弹出运算即可. bool isOperator(string &op) { //注意用法 && string("+-* ...

  4. Evaluate Reverse Polish Notation(堆栈)

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  5. 【leetcode】917. Reverse Only Letters(双指针)

    Given a string s, reverse the string according to the following rules: All the characters that are n ...

  6. 【leetcode】Search for a Range(middle)

    Given a sorted array of integers, find the starting and ending position of a given target value. You ...

  7. 【leetcode】Swap Nodes in Pairs (middle)

    Given a linked list, swap every two adjacent nodes and return its head. For example,Given 1->2-&g ...

  8. 【leetcode】Linked List Cycle II (middle)

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Foll ...

  9. 【leetcode】Path Sum I & II(middle)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

随机推荐

  1. TTFB-首字节时间简介

    百度站长工具里看到有一个"首字节时间"的建议,第一次听说,还真不知道是什么东东.百度站长工具里面的解释是:"浏览器开始收到服务器响应数据的时间=后台处理时间+重定向时间, ...

  2. 【AngularJS】—— 10 指令的复用

    前面练习了如何自定义指令,这里练习一下指令在不同的控制器中如何复用. —— 来自<慕课网 指令3> 首先看一下一个小例子,通过自定义指令,捕获鼠标事件,并触发控制器中的方法. 单个控制器的 ...

  3. WPF:自定义路由事件的实现

    路由事件通过EventManager,RegisterRoutedEvent方法注册,通过AddHandler和RemoveHandler来关联和解除关联的事件处理函数:通过RaiseEvent方法来 ...

  4. centos7 静态ip设置

    TYPE=Ethernet BOOTPROTO=static DEFROUTE=yes IPV4_FAILURE_FATAL=no IPV6INIT=yes IPV6_AUTOCONF=yes IPV ...

  5. PHP Socket实现websocket(三)Stream函数

    除了socket函数也可以使用stream函数来实现服务器与客户端. 参考PHP 的Stream实现服务器客户端模型: http://php.net/manual/en/book.stream.php ...

  6. 如何开启telnet 23端口

    netstat -tnl|grep 23 查看23端口是否开启 或者 chkconfig --list|grep telnet 检查telnet状态 如果关闭状态, 开启:chkconfig --le ...

  7. java中二进制和流的相互转换

    流转二进制 public static byte[] toByteArray(InputStream in) throws IOException { ByteArrayOutputStream ou ...

  8. iOS开发——高级篇——内存分析,Instruments

    一.内存分析 1.静态内存分析(Analyze)不运行程序,直接对代码进行内存分析,查看代码是否有内存泄露优点:分析速度快,并且可以对所有的代码进行内存分析缺点:分析结果不一定准确(没有运行程序,根据 ...

  9. BZOJ3052——糖果公园

    0.题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3052 1.题目大意:给定一颗n个点的无根树,每个点有一个颜色,要进行q次操作,有两种操 ...

  10. Cocos2d-x 3.2 项目源代码从Mac打包到安卓教程【转自:http://www.2cto.com/kf/201410/342649.html】

    当我们用Xcode写好一个项目的源码之后,如何将它导入到安卓手机中呢?下面我来给大家一步一步讲解: 首先,我们打开终端,cd到Cocos2d-x 3.2文件夹中(注意不是你写的项目文件夹,而是官方项目 ...