博客
关于我
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/

你可能感兴趣的文章
poj 3485 区间选点
查看>>
poj 3518 Prime Gap
查看>>
poj 3539 Elevator——同余类bfs
查看>>
Qt笔记——官方文档全局定义(三)Macros宏
查看>>
poj 3628 Bookshelf 2
查看>>
Qt笔记——官方文档全局定义(一)Types数据类型
查看>>
POJ 3670 DP LIS?
查看>>
POJ 3683 Priest John's Busiest Day (算竞进阶习题)
查看>>
POJ 3988 Selecting courses
查看>>
POJ 4020 NEERC John's inversion 贪心+归并求逆序对
查看>>
poj 4044 Score Sequence(暴力)
查看>>
POJ 基础数据结构
查看>>
POJ 题目3020 Antenna Placement(二分图)
查看>>
Poj(1797) Dijkstra对松弛条件的变形
查看>>
POJ--2391--Ombrophobic Bovines【分割点+Floyd+Dinic优化+二分法答案】最大网络流量
查看>>
Qt笔记——SQLite初探QSqlDatabase QSqlQuery
查看>>
POJ-1163-The Triangle
查看>>
POJ-Fence Repair 哈夫曼树
查看>>
poj1061 - 同余方程,二元一次不定方程
查看>>
Qt笔记——SQLite再探
查看>>