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 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...
随机推荐
- JQuery之proxy实现绑定代理
在javascript中,this指代的对象时常会变化,这会造成程序,混乱,一般做法就是先将this保存在一个变量中,就不怕她变了,我们先看一个小例子 var A = function(){ this ...
- .Net中的Socket通讯
.NetFrameWork为Socket通讯提供了System.Net.Socket命名空间,在这个命名空间里面有以下几个常用的重要类分别是: ·Socket类 这个低层的类用于管理连接,WebReq ...
- php获取网页中图片并保存到本地的代码
php获取网页中图片并保存到本地的代码,将网页中图片保存本地文件夹: <?php /** * 获取网页中图片,并保存至本地 * by www.jbxue.com */ header(" ...
- 修改Win7远程桌面端口
Win7与XP不同,在开启远程桌面修改端口后是无法直接访问的,原因是还未修改远程桌面在防火墙入站规则中的端口号. 修改远程桌面端口: [HKEY_LOCAL_MACHINE/SYSTEM/Curren ...
- 给view 添加事件
//绑定图片点击事件 UITapGestureRecognizer *g=[[UITapGestureRecognizeralloc]initWithTarget:selfaction:@select ...
- Delphi XE5教程7:单元引用和uses 子句
内容源自Delphi XE5 UPDATE 2官方帮助<Delphi Reference>,本人水平有限,欢迎各位高人修正相关错误! 也欢迎各位加入到Delphi学习资料汉化中来,有兴趣者 ...
- 一道关于比赛胜负的Sql查询题目
以前做过一道题目,一直没有来得及总结下来.贴图: 记得以前曾经找到了两种方法,今天试了一下,还是可以的,贴出过程: 下面是具体的查询方法: 原来放的是图片,今天又练习了一下,附代码: create T ...
- hdu 5719 BestCoder 2nd Anniversary B Arrange 简单计数问题
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5719 题意:一个数列为1~N的排列,给定mn[1...n]和mx[1...n],问有符合的排列数为多少 ...
- 如何设置让SFTP的用户限制在某个目录下
通常SFTP的任何用户登录之后能看到整个系统的文件目录,这样很不安全. 通过chroot我们可以将某个用户登录SFTP后只能在某个限定的目录下操作,这样可以更安全.我们来看看怎么设置. 1.创建一个用 ...
- Jboss wildfly add JDBC driver
Jboss wildfly 添加 JDBC driver 我这里使用的是 wildfly-8.0.0.Final 第一步: 首先在modules里面添加mysql的驱动包 例如:modules\sy ...