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. 使用pygal 做chart图的经验分享

    看到小芮介绍了pygal文章后, http://rfyiamcool.blog.51cto.com/1030776/1378400, 我一直搞数据工作, 所以对于这种数据的展现很有兴趣. 做了点研究, ...

  2. NUGet的诞生与使用

    本文引用地址:http://msdn.microsoft.com/zh-cn/magazine/hh547106.aspx NuGet 使用 NuGet 管理项目库 Phil Haack 无论多么努力 ...

  3. WebSocket帧数据 解码/转码

    数据从浏览器通过websocket发送给服务器的数据,是原始的帧数据,默认是被掩码处理过的,所以需要对其利用掩码进行解码. 从服务器发送给浏览器的数据是默认没有掩码处理的,只要符合一定结构就可以了.具 ...

  4. .assetbundle 和.unity3d 好处

    .assetbundle 资源文件 .unity3D  场景文件 xml.json 静态存储和 还原 AssetBuddle 优点:减小压缩包.资源更新.分开安装包和数据包.AssetBuddle加密 ...

  5. iOS网络学习之“远离NSURLConnection 走进NSURLSession”

    目前,在iOS的开发中,NURLConnection已经成为了过去式,现在的NSURLConnection已经deprected(iOS7之后),取而代之的是NSURLSession.而且AFNetw ...

  6. Linux 之 shell 比较运算符

    运算符 描述 示例 文件比较运算符 -e filename 如果 filename 存在,则为真 [ -e /var/log/syslog ] -d filename 如果 filename 为目录, ...

  7. OpenCv椭圆皮肤模型

    Mat input_image; Mat output_mask; Mat output_image; void main() { VideoCapture cam(); if (!cam.isOpe ...

  8. C++笔试题(转)

    http://blog.csdn.net/hxz_qlh/article/details/16864567 这里面列举的题考察的东西都非常细,包括strcpy,字符串,大.小端的判断,很容易犯错,值得 ...

  9. opencv中的视频的读入

    #include"stdafx.h"#include"opencv2/opencv.hpp" using namespace cv;int g_slider_p ...

  10. 一个CMS案例实战讲解PHP代码审计入门

    前言 php代码审计介绍:顾名思义就是检查php源代码中的缺点和错误信息,分析并找到这些问题引发的安全漏洞. 1.环境搭建: 工欲善其事必先利其器,先介绍代码审计必要的环境搭建 审计环境 window ...