博客
关于我
150. 逆波兰表达式求值 (栈)
阅读量:376 次
发布时间:2019-03-05

本文共 986 字,大约阅读时间需要 3 分钟。

分析

本题与计算器那道题的区别在于表达式的形式。

本题是后缀表达式,不需要额外的处理,可以直接让两个数字出栈进行运算。
而计算器那道题是中缀表达式,需要对符号的优先级进行判断。

C++ 代码

class Solution {public:    stack
stk1; // 只需一个数字栈即可 bool dg(char c) { // 判断是否为合法数字 return (c >= '0' && c <= '9'); } int getc(string c) { // 判断符号类型 if (c == "+") return 1; if (c == "-") return 2; if (c == "*") return 3; return 4; } int evalRPN(vector
&s) { int n = s.size(); for (int i = 0; i < n; ++i) { if (dg(s[i][0]) || (s[i].size() > 1 && s[i][0] == '-')) { // 数字或负数 stk1.push(stoi(s[i])); } else { // 运算符 int a = stk1.top(); stk1.pop(); int b = stk1.top(); stk1.pop(); int c = getc(s[i]); if (c == 1) b += a; if (c == 2) b -= a; if (c == 3) b *= a; if (c == 4) b /= a; stk1.push(b); } } return stk1.top(); // 结果在栈顶 }};

转载地址:http://poag.baihongyu.com/

你可能感兴趣的文章
NOIP模拟测试19
查看>>
NOIp模拟赛二十九
查看>>
Nokia5233手机和我装的几个symbian V5手机软件
查看>>
Non-final field ‘code‘ in enum StateEnum‘
查看>>
none 和 host 网络的适用场景 - 每天5分钟玩转 Docker 容器技术(31)
查看>>
None还可以是函数定义可选参数的一个默认值,设置成默认值时实参在调用该函数时可以不输入与None绑定的元素...
查看>>
NOPI读取Excel
查看>>
NoSQL&MongoDB
查看>>
NoSQL介绍
查看>>
Notadd —— 基于 nest.js 的微服务开发框架
查看>>
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>