lintcode 中等题:Evaluate Reverse Polish notation逆波兰表达式求值
题目
在逆波兰表达法中,其有效的运算符号包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
什么是逆波兰表达式?
解题
利用栈的解题
当是数字的时候入栈,当不是数字的时候连续两次出栈,对出栈的数据进行运算,运算结果再入栈
如何判定是数字?
根据正则还是比较简单的
str.matches("\\d+") == true
需要注意的是:是负数的情况
str.substring(0,1).equals("-")&& str.substring(1,str.length()).matches("\\d+") == true
我是先判定第一个字符是“-” ,再判定是否是数字
后面就是对于四则运行就简单,注意非法字符,和除0的情况,我是直接返回最大值。
还有个要注意的是当在运算的过程中栈空了,说明输入的不是有效的逆波兰表达式
public class Solution {
/**
* @param tokens The Reverse Polish Notation
* @return the value
*/
public int evalRPN(String[] tokens) {
// Write your code here
if(tokens == null)
return 0;
if(tokens.length == 1)
return Integer.valueOf(tokens[0]);
Stack<Integer> stack = new Stack<Integer>();
for(int i =0;i< tokens.length ;i++){
String str = tokens[i];
if(str.matches("\\d+") == true ||
str.substring(0,1).equals("-")&&str.substring(1,str.length()).matches("\\d+") == true){
int num = Integer.valueOf(str);
stack.push(num);
}else{
if(stack.empty()){
System.out.println("the stack is empty");
return -1;
}
int num2 = stack.pop();
int num1 = stack.pop();
int res = calculate(num1,num2,str);
stack.push(res);
}
}
return stack.pop();
}
public int calculate(int num1,int num2,String symbol){
if(symbol.equals("+"))
return num1+ num2;
if(symbol.equals("-"))
return num1 - num2;
if(symbol.equals("*"))
return num1*num2;
if(symbol.equals("/")){
if(num2!=0){
return num1/num2;
}else{
return Integer.MAX_VALUE;
}
}else{
return Integer.MAX_VALUE;
}
}
}
Java Code
总耗时: 11103 ms
Python程序 出现1/-123 等于-1的问题,表示手工解决太愚蠢,程序如下
class Solution:
# @param {string[]} tokens The Reverse Polish Notation
# @return {int} the value
def evalRPN(self, tokens):
# Write your code here
if tokens == None:
return 0
if len(tokens) == 1:
return int(tokens[0])
stack = []
# print 13//3
# print 13/3
# print 6/(135) 0
# print 6/(-135) -1
for tk in tokens:
if tk.isdigit() or tk[0] == '-' and tk[1:].isdigit():
stack.append(int(tk))
else:
num2 = stack.pop()
num1 = stack.pop()
num = self.calculate(num1,num2,tk)
stack.append(num)
if(len(tokens) == 13):
print stack
return stack.pop() def calculate(self,num1,num2,sign):
if sign =='-':
return num1 - num2
elif sign == '+':
return num1 + num2
elif sign == '*':
return num1 * num2
elif sign == '/':
if num2!=0:
return -num1//num2
else:
return 0
else:
return 0
Python Code
lintcode 中等题:Evaluate Reverse Polish notation逆波兰表达式求值的更多相关文章
- 150 Evaluate Reverse Polish Notation 逆波兰表达式求值
求在 逆波兰表示法 中算术表达式的值.有效的运算符号包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰计数表达.例如: ["2", "1&quo ...
- Leetcode150. Evaluate Reverse Polish Notation逆波兰表达式求值
根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰表达式. 说明: 整数除法只保留整数部分. 给定逆波兰表达式总是有效的.换句话说 ...
- 150. Evaluate Reverse Polish Notation逆波兰表达式
[抄题]: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are ...
- 150. Evaluate Reverse Polish Notation(逆波兰表达式)
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)
原题链接:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题目描述: Evaluate the value of a ...
- Evaluate Reverse Polish Notation(逆波兰式)
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- [leetcode]150. Evaluate Reverse Polish Notation逆波兰表示法
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- Java Evaluate Reverse Polish Notation(逆波兰式)
表情:: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) ...
- LeetCode 150. 逆波兰表达式求值(Evaluate Reverse Polish Notation) 24
150. 逆波兰表达式求值 150. Evaluate Reverse Polish Notation 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...
随机推荐
- javascript里面技巧整理
web develop tools secrets: http://jinlong.github.io/blog/2013/08/29/devtoolsecrets/ 1.Date new Date( ...
- 我的总结SVN的使用
SVN平时在用时,一般要做到早上一次更新,中间每做出一个模块就要提交,就是一次更新,多次提交, SVN在修改公共类,配置文件时一定要注意,如果修改的是配置文件中的东西,这样修改完之后一定要提交, 如果 ...
- eclipse 4 rcp: java.lang.RuntimeException: No application id has been found.
错误详情: java.lang.RuntimeException: No application id has been found. at org.eclipse.equinox.internal. ...
- php curl post
public static function curlPost($url, $data=array()) { $ch = curl_init(); if (is_array ...
- 如何重建Octopress本地环境
# 安装rvm, ruby, bundler 略 # 克隆octopress $ git clone git://github.com/imathis/octopress.git octopress ...
- exec 和 source的区别
source 就是让 script 在当前 shell 内执行.而不是产生一个 sub-shell 来执行.由exec 也是让 script 在同一个行程上执行,但是原有行程则被结束了. source ...
- C# 链接Sql和Access数据库语句
1.sql数据库: 1.1.链接数据语句:server=localhost;database=Data; uid=sa;pwd=123; 或 Data Source=localhost;DataBas ...
- [原创]PostgreSQL Plus Advince Server在 HA环境中一对多的Stream Replication配置(一)
内容较多,开篇作为说明和目录. 实验环境规划:服务器:IBM x3500 m3三台其中两台用作HA,另外一台安装VMware ESXi安装两个虚机做Stream Replication.NAS存储IP ...
- 在Linux下写一个简单的驱动程序
本文首先描述了一个可以实际测试运行的驱动实例,然后由此去讨论Linux下驱动模板的要素,以及Linux上应用程序到驱动的执行过程.相信这样由浅入深.由具体实例到抽象理论的描述更容易初学者入手Linux ...
- Mysql ubuntu下的安装卸载
删除 mysql sudo apt-get autoremove --purge mysql-server-5.0sudo apt-get remove mysql-serversudo apt-ge ...