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. [Shoi2007]Bookcase 书柜的尺寸 dp

    这道dp算是同类型dp中比较难的了,主要难点在于设置状态上: 如果像平时那样设置,必定爆空间没商量: 下面是一种思路: 先把输入进来的数据按h从大到小排序,这样就可以大大减少状态数, 然后设f[i][ ...

  2. discuzx完全自定义设计模板门户首页,栏目,专题模板方法

    第一种:门户首页模板(index.htm,保存于templatedefaultportal) <!--{subtemplate common/header}--> <style id ...

  3. HttpWatch 安装后在IE上打开

    启动浏览器, 在空白地方左键,  显示出菜单栏 菜单栏中选择"查看">"浏览器栏">"HttpWatch"启动HttpWatch ...

  4. 用HAProxy和KeepAlived构建高可用的反向代理

      用HAProxy和KeepAlived构建高可用的反向代理 用HAProxy和KeepAlived构建高可用的反向代理 前言对于访问量较大的网站来说,随着流量的增加单台服务器已经无法处理所有的请求 ...

  5. 分布式数据存储 - Zabbix监控MySQL性能

    Zabbix如何监控mysql性能,我们可以使用mysql自带的模板,可以监控如下内容:OPS(增删改查).mysql请求流量带宽,mysql响应流量带宽,最后会附上相应的监控图! 编写check_m ...

  6. acdream1116 Gao the string!(扩展KMP)

    今天是字符串填坑的一天,首先填的第一个坑是扩展KMP.总结一下KMP和扩展KMP的区别. 在这里s是主串,t是模式串. KMP可以求出的是以s[i]为结尾的串和 t前缀匹配的最长的长度.假如这个长度是 ...

  7. POJ 2891 Strange Way to Express Integers (解一元线性方程组)

    求解一元线性同余方程组: x=ri(mod ai) i=1,2,...,k 解一元线性同余方程组的一般步骤:先求出前两个的解,即:x=r1(mod a1)     1x=r2(mod a2)     ...

  8. 【转】dip,px,pt,sp 的区别

    dip: device independent pixels(设备独立像素). 不同设备有不同的显示效果,这个和设备硬件有关,一般我们为了支持WVGA.HVGA和QVGA 推荐使用这个,不依赖像素. ...

  9. ExtJs之Ext.core.DomQuery

    <!DOCTYPE html> <html> <head> <title>ExtJs</title> <meta http-equiv ...

  10. ant+jmeter+crontab实现自动化性能测试

    准备工作: 1.下载jmeter(我下载的apache-jmeter-2.13.zip) 2.配置jmeter环境变量,即path前添加jmeter的bin路径) 3.下载ant(我使用的apache ...