leetcode--Evaluate Reverse Polish Notation
来源:互联网 发布:社交网络上的跟风行为 编辑:程序博客网 时间:2024/06/05 20:55
class Solution {public: int evalRPN(vector<string>& tokens) { stack<int> number; for(int i = 0 ; i < tokens.size();i++) { if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { int n1 = 0; int n2 = 0; n1 = number.top(); number.pop(); n2 = number.top(); number.pop(); if(tokens[i] == "+") number.push(n1+n2); else if(tokens[i] == "-") number.push(n2-n1); else if(tokens[i] == "*") number.push(n1*n2); <span style="color:#ff0000;">else if(tokens[i] == "/")</span>
<span style="color:#ff0000;"> {//之前未判断分母为零的情况</span>
<span style="color:#ff0000;"> if(n1 != 0)</span>
<span style="color:#ff0000;"> number.push(n2/n1);</span>
} } else { number.push(atoi(tokens[i].c_str())); } }
if(!number.empty())//加上判断条件 return number.top(); }};
以上代码运行出现错误:Last executed input: ["0","3","/"]
原因在于未判断分母为0的情况。
小结:这个题本身难度系数不高,只要学过stack的人都会想到,毕竟数据结构的书上有相关的内容,但是细节问题值得注意。
1)vector<string> & tokens这个参数是字符串的容器,里面的运算符均是字符串形式存储 : "+" "-" "*" "/"并非单引号的一个字符,就相当于‘a’代表字符a,但是”a“其实是字符串'a'+'\0'
2) 使用atoi()函数进行字符转为整数时出错,在于atoi()的参数是const char* str,但是tokens却是string类型。
注意,与char*不同的是,string不一定以NULL('\0')结束。string长度可以根据length()得到,string可以根据下标访问。所以,不能将string直接赋值给char*。如果要将string直接转换成const char *类型。string有2个函数可以运用。
一个是.c_str(),一个是data成员函数。
具体关于char* str 和 string 之间的关系见http://blog.csdn.net/cogbee/article/details/8931838
3)刚开始打算用switch结构来对运算符进行判别,但是最后发现在C++中switch的选择因子只能是整数。所以最终转为if---else结构。
4)还要考虑特殊情况,比如这题的分母为0的时候。
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
- Poj 3278 Catch That Cow
- CryptoAPI简介
- 实现页面图片的延时异步加载
- REST技术第三步 @BeanParam的使用
- hdoj 1501 Zipper
- leetcode--Evaluate Reverse Polish Notation
- android关于canvas.rotate()研究
- SparkML实战之五:SVM
- java160107ThreadTest
- 开个博客记录日语学习
- 数据库-表连接
- Oracle树查询(查询所有子节点,父节点等等)
- Postman 简单实用 提高编程效率
- 如何移植openwrt系统