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. HDOJ 1711 Number Sequence

    Number Sequence Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  2. Flash相册-------3D旋转应用

    1.图层一,图片1,转换为元件 2.3D旋转工具,变形--->y->180

  3. ubuntu安装php常见错误集锦

    一.configure 报错 1.错误类型: Configure: error: Please reinstall the libcurl distribution-easy.h should be ...

  4. MongoDB—— 读操作 Core MongoDB Operations (CRUD)

    本文主要介绍内容:从MongoDB中请求数据的不同的方法 Note:All of the examples in this document use the mongo shell interface ...

  5. HashMap原理分析

    HashMap 实现Map.Cloneable.Serializable接口,继承AbstractMap基类. HashMap map = new HashMap(); 实例化一个HashMap,在构 ...

  6. iOS开发——UI基础-提示框

    提示框的种类有很多,废话不多说,直接上代码 一.文本提示框 运行结果如下: 代码实现如下: @interface ViewController () // 添加方法 - (IBAction)add; ...

  7. 如何使用coding.net

        由于我有一位十分聪明能干的室友会使用coding.net,于是我决定奉献一下室友的智慧,告诉大家如何使用conding.net上交作业.(如有说错的地方希望大家可以指出来) 首先登陆codin ...

  8. 深入Activity,Activity启动模式LaunchMode完全解析

    转载请注明出处:http://blog.csdn.net/linglongxin24/article/details/53221384本文出自[DylanAndroid的博客] 在平时的开发中,我们可 ...

  9. linux中diff命令用法

    diff 命 令是 linux上非常重要的工具,用于比较文件的内容,特别是比较两个版本不同的文件以找到改动的地方.diff在命令行中打印每一个行的改动.最新版 本的diff还支持二进制文件.diff程 ...

  10. linux下QtCreator无法输入中文的情况

    解决linux下QtCreator无法输入中文的情况 本文由乌合之众 lym瞎编,欢迎转载 blog.cnblogs.net/oloroso 本文由乌合之众 lym瞎编,欢迎转载 my.oschina ...