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 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...
随机推荐
- MDX : Non Empty v/s NonEmpty
MDX : Non Empty v/s NonEmpty User Rating: / 50 PoorBest Written by Jason Thomas Friday, 07 May 20 ...
- react-native-vector-icons 安装
react-native-vector-icons 是可以直接使用图片名就能加载图片的第三方,类似于web的iconfont矢量图,使用很方便, 你不需要在工程文件夹里塞各种图片, 节省很多空间,下面 ...
- CSS居中的实现用法实例
转载的一篇文章,讲解css内容居中的. 网上有关css 居中的文章不胜枚举,不过大多没有做系统的总结.这里分享的这篇有关css居中的文章,个人感觉不错,值得收藏. 一.水平居中1,将元素水平居中(us ...
- apache问题集锦
一.如何防止别的网站盗连我们网站的图片.CSS.JS等资源? RewriteCond %{HTTP_REFERER} !test.test.com [NC] #RewriteRule \.(gif|j ...
- jdbc 连接 mysql 获取 数据集 条数
package nona; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; im ...
- Android之“Unfortunately,xxx has stopped!”
初学Android遇到Unfortunately,xxx has stopped!真是一件让人头疼的事情,下面就遇到的两种可能情况给出解决方案.通常遇到的情况在于由一个Activity跳转至另一个Ac ...
- MVC C# 调用存储过程
SqlParameter[] param ={ new SqlParameter("@SignInfoId ",SqlDbType.Int), new SqlParameter(& ...
- ibatis.net demo
1. download ibatis.nethttps://code.google.com/p/mybatisnet/ 2. add all dll as reference to your proj ...
- c#之委托和事件的区别
1.什么是委托,这里就不做介绍了,如果想了解可以查看博客:http://www.cnblogs.com/xiaoxiaogogo/p/3571494.html 下面开始对事件进行介绍 1.定义事件以及 ...
- JDBC 学习笔记(一)—— 基础知识 + 分页技术
本文目录: 1.JDBC简介 2.使用JDBC的步骤——第一个JDBC程序 3.DriverManager ——加载数据库驱动 4.数据库URL ——标识数据库的 ...