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

分析:

/*-----Reverse Polish Notation(逆波兰表达式),又叫做后缀表达式。在通常的表达式中,二元运算符总是置于与之相关的两个运算对象之间,这种表示法也称为中缀表示。波兰逻辑学家J.Lukasiewicz于1929年提出了另一种表示表达式的方法,按此方法,每一运算符都置于其运算对象之后,故称为后缀表示。

优势

它的优势在于只用两种简单操作,入栈和出栈就可以搞定任何普通表达式的运算。其运算方式如下:
如果当前字符为变量或者为数字,则压栈,如果是运算符,则将栈顶两个元素弹出作相应运算,结果再入栈,最后当表达式扫描完后,栈里的就是结果。-----*/
 
思路:利用堆栈来解决这道题。注意,我们还需要实现整数与字符串之间的相互转换。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> cache; for(int i = 0 ; i < tokens.size(); i++){
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){
int num2 = cache.top();
cache.pop();
int num1 = cache.top();
cache.pop();
cache.push(calculate(num1, num2, tokens[i]));
}
else{
cache.push(str2int(tokens[i]));
}
} return cache.top();
} int str2int(string s){
int result=0;
int base=1;
for(int i = s.size()-1;i>=0;i--){
if(s[i] == '-' && i == 0){
result *= -1;
}
else if(s[i] >= '0' && s[i] <= '9'){
result += base * (s[i] - '0');
base *= 10;
}
}
return result;
} int calculate(int num1, int num2, string op){
if(op == "+"){
return num1 + num2;
}
else if(op == "-"){
return num1 - num2;
}
else if(op == "*"){
return num1 * num2;
}else if(op == "/"){
return num1 / num2;
}
}
};

 其他方法:

class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (auto t : tokens) { //自动类型推断
if (t == "+" || t == "-" || t == "*" || t == "/") {
int y = s.top(); s.pop();
int x = s.top(); s.pop();
int z = 0;
switch (t.front()) {
case '+' :
z = x + y;
break;
case '-' :
z = x - y;
break;
case '*' :
z = x * y;
break;
case '/' :
z = x / y;
break;
}
s.push(z);
} else {
s.push(stoi(t)); //字符串怎么转数值用函数 std::stoi()函数原型:
                                          //int stoi (const string& str, size_t* idx = 0, int base = 10); base 是进制                                                 
            }
}
return s.top();
}
};

  使用is_operator更简洁:

class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stn;
for(auto s:tokens) {
if(s.size()>1 || isdigit(s[0])) stn.push(stoi(s));
else {
auto x2=stn.top(); stn.pop();
auto x1=stn.top(); stn.pop();
switch(s[0]) {
case '+': x1+=x2; break;
case '-': x1-=x2; break;
case '*': x1*=x2; break;
case '/': x1/=x2; break;
}
stn.push(x1);
}
}
return stn.top();
}
};

  

Evaluate Reverse Polish Notation(堆栈)的更多相关文章

  1. 【leetcode】Evaluate Reverse Polish Notation

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

  2. [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式

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

  3. LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation

    LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation Evaluate the value of an arithm ...

  4. 【LeetCode练习题】Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  5. leetcode - [2]Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Total Accepted: 24595 Total Submissions: 123794My Submissions Evalu ...

  6. 【LeetCode】150. Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  7. LeetCode: Evaluate Reverse Polish Notation 解题报告

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  8. LeetCode 150. 逆波兰表达式求值(Evaluate Reverse Polish Notation) 24

    150. 逆波兰表达式求值 150. Evaluate Reverse Polish Notation 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...

  9. 【LeetCode】150. Evaluate Reverse Polish Notation 解题报告(Python)

    [LeetCode]150. Evaluate Reverse Polish Notation 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/ ...

  10. 【刷题-LeetCode】150 Evaluate Reverse Polish Notation

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

随机推荐

  1. 【BZOJ】【3530】【SDOI2014】数数

    AC自动机/数位DP orz zyf 好题啊= =同时加深了我对AC自动机(这个应该可以叫Trie图了吧……出边补全!)和数位DP的理解……不过不能自己写出来还真是弱…… /************* ...

  2. Hdu 1010 Tempter of the Bone 分类: Translation Mode 2014-08-04 16:11 82人阅读 评论(0) 收藏

    Tempter of the Bone Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Othe ...

  3. CSS字体选择问题

    在西方国家的字母体系,分成两大字族:serif 及 sans serif.其中 typewriter 打字机字体,虽然也是 sans serif,但由于他是等距字,所以另独立出一个 Typewrite ...

  4. 国内外php主流开源cms、SNS、DIGG、RSS、Wiki汇总

    今年国内PHP开源CMS内容管理系统从程序框架,模版加载到程序功能上都有很大的进步,大部分都采用了自定义模块,自定义模型的方式,同时提供各个CMS都提供不同的特色功能,CMS内容管理系统一直影响着互联 ...

  5. js获取,设置FCKeditor内容

    // 获取编辑器中HTML内容 function getEditorHTMLContents(EditorName) {     var oEditor = FCKeditorAPI.GetInsta ...

  6. ASP.NET的一套笔试题

    1.    自定义控件如何做?答:自定义控件,跟HtmlControl或WebControl相似,编译后可以添加引用到工具栏里面,直接用鼠标拖动使用.2.界面的布局?答:表格,div3.程序的执行过程 ...

  7. CSS自定义文件上传按钮

    今天一同事问我文件上传按钮的问题,情况是这样的,他页面上有3个按钮,分为左中右三个,左边的位按钮甲,右边的位按钮乙,而中间的就是个文件选择按钮,情况大概是这个样子的: 两边的按钮都有了样式,但中间的选 ...

  8. JS中showModalDialog 详细使用(转)

    基本介绍: showModalDialog()         (IE 4+ 支持) showModelessDialog()      (IE 5+ 支持) window.showModalDial ...

  9. 用wget实现cookie欺骗

    用wget实现cookie欺骗 . 分析登录界面的html代码 页面在 http://bbs.linuxeden.com/ <form. id="loginform" met ...

  10. ***PHP implode() 函数,将数组合并为字符串;explode() 函数,把字符串打散为数组

    实例 把数组元素组合为字符串: <?php $arr = array('Hello','World!','I','love','Shanghai!'); echo implode(" ...