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. PHP CLI下接受参数的几种方法

    PHP CLI(命令行模式下)接受参数有多种方法: (1)使用$argv接受参数 <?php //变量仅在 register_argc_argv 打开时可用. print_r($argc); / ...

  2. Apache索引目录浏览的学习笔记

    在浏览一些镜像文件站的时候,会发现网站目录是可以浏览文件(夹)列表的.举两个例子:网易开源镜像:Ubuntu.只要 Web 服务器是基于 Apache 的网站都可以开启或禁止索引(目录浏览),那么如何 ...

  3. document.all的详细解释(document.all基本上所有浏览器可用!)

    从何而来从IE4开始IE的object model才增加了document.all对象,MSDN中也对 Object.all 有详细的说明,Object.all是个HTMLCollection,不是数 ...

  4. 【MongoDB】MongoDb的“not master and slaveok=false”错误及解决方法

    链接mongodb报错如下 2016-03-14T16:26:00.912+0800 E QUERY [thread1] Error: listDatabases failed:{ "ok& ...

  5. 增值税——基础知识

    一.增值税的概念 增值税是对从事销售货物或者提供加工.修理修配劳务以及从事进出口货物的单位和个人取得的增值额为课税对象征收的一种税. 增值额是指纳税人在生产.经营或劳务活动中所创造的新增价值,即纳税人 ...

  6. android 读取SQLite android could not open the database in read/write mode错误

    由于AndroidManifest.xml文件中uses-permission没有设置权限问题 <uses-permission android:name="android.permi ...

  7. 设置p标签自动换行

    <body>     <p style="width:20px;height:100px;background-color:#069; word-wrap: break-w ...

  8. 关于NGUI与原生2D混用相互遮盖的问题心得

    http://www.fzgh.org.cn/zuixindianying/144224.html Native2D自己可以使用Sort Layer来排序,每层又有不同的Order In Layer, ...

  9. ACCESS延时注入

    这也算是个新知识吧.今天遇到个站,实实在在存在注入,但是弄不出字段.本应该可以用便宜注入.但是不知道为什么就是就是弄不出来. 大家如果有兴许可以加学习交流群:281245781 交流一下吧. Payl ...

  10. 编码(Code)

    很遗憾,直接搜索Code或者编码是很难得找到这本书的,我也是无意中才接触到本书. 第一次读本书,对各方面的知识都不算很懂,觉得很多地方都写的太多浅显,好像本该就是这样子,一个编码系统说的那么麻烦干嘛, ...