LeetCode | Evaluate Reverse Polish Notation
来源:互联网 发布:网络自学英语 编辑:程序博客网 时间:2024/06/07 00:41
题目:
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
思路:
逆波兰式计算等式非常容易,利用堆栈即可完成。另外,程序中还需要实现整数与字符串之间的相互转换。
代码
“`
class Solution {
public:
int evalRPN(vector &tokens) {
int result = 0; int i; stack<int> opd; //存储操作数 int size = tokens.size(); for(i=0;i<size;i++) { if(!strcmp(tokens[i].c_str(),"+")) { int rOpd = opd.top(); //右操作数 opd.pop(); int lOpd = opd.top(); //左操作数 opd.pop(); result = lOpd+rOpd; opd.push(result); } else if(!strcmp(tokens[i].c_str(),"/")) { int rOpd = opd.top(); opd.pop(); int lOpd = opd.top(); opd.pop(); result = lOpd/rOpd; opd.push(result); } else if(!strcmp(tokens[i].c_str(),"-")) { int rOpd = opd.top(); opd.pop(); int lOpd = opd.top(); opd.pop(); result = lOpd-rOpd; opd.push(result); } else if(!strcmp(tokens[i].c_str(),"*")) { int rOpd = opd.top(); opd.pop(); int lOpd = opd.top(); opd.pop(); result = lOpd*rOpd; opd.push(result); } else { opd.push(atoi(tokens[i].c_str())); } } return opd.top();}
};
思考
1、本题用的是栈
2、char *字符串之间的比较用函数strcmp()函数。若用==比较,则默认比较的是地址
char 字符用==符号
3、对于不同的编译器,对string 类型处理不一样。有的编译器会把char 类型数据默认转换为string,有的则不会。所以对于string==char* 的处理需要注意。
阅读全文
0 0
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Leetcode:Evaluate Reverse Polish Notation
- mac 环境变量配置
- oracle 字符串转多行
- 数据结构-栈-数组实现对头的双栈
- #学志#Ubuntu安装lamp(Apache2+MySQL+PHP)
- Lintcode51 Previous Permutation solution 题解
- LeetCode | Evaluate Reverse Polish Notation
- 4-12 判断奇偶性 (10分)
- caffe 追加新层new layer添加.cu文件问题--无法解析的外部符号
- FreeMarker
- iOS开发学习专题-基础知识(四) NSNumber容器 NSData数据 NSData转换的详细使用方式
- 通过WifiManager可以实现对wifi进行操作,实现wifi自动连接等一些功能
- window命令行直接打开手机的APP应用
- 如何使用命令行在github搭建项目?
- 基于Unity3D(UGUI)的背包系统<二>