题目

在逆波兰表达法中,其有效的运算符号包括 +-*/ 。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。

样例

["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逆波兰表达式求值的更多相关文章

  1. 150 Evaluate Reverse Polish Notation 逆波兰表达式求值

    求在 逆波兰表示法 中算术表达式的值.有效的运算符号包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰计数表达.例如:  ["2", "1&quo ...

  2. Leetcode150. Evaluate Reverse Polish Notation逆波兰表达式求值

    根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, / .每个运算对象可以是整数,也可以是另一个逆波兰表达式. 说明: 整数除法只保留整数部分. 给定逆波兰表达式总是有效的.换句话说 ...

  3. 150. Evaluate Reverse Polish Notation逆波兰表达式

    [抄题]: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are ...

  4. 150. Evaluate Reverse Polish Notation(逆波兰表达式)

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  5. [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)

    原题链接:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题目描述: Evaluate the value of a ...

  6. Evaluate Reverse Polish Notation(逆波兰式)

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  7. [leetcode]150. Evaluate Reverse Polish Notation逆波兰表示法

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  8. Java Evaluate Reverse Polish Notation(逆波兰式)

    表情:: ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) ...

  9. LeetCode 150. 逆波兰表达式求值(Evaluate Reverse Polish Notation) 24

    150. 逆波兰表达式求值 150. Evaluate Reverse Polish Notation 题目描述 根据逆波兰表示法,求表达式的值. 有效的运算符包括 +, -, *, /.每个运算对象 ...

随机推荐

  1. 批处理测试局域网网络连通性ping1-255

    for /l %%1 in (1 1 255)do ping /n 1 192.168.1.%%1       ##bat下 运行 for /l %i in (1,1,254) do ping -n ...

  2. WPF 绑定五(本身就是数据源)

    xaml: <Window x:Class="WpfApplication1.Window5" xmlns="http://schemas.microsoft.co ...

  3. $(document).height()、$("body").height()、$(window).height()区别和联系

    前言:在此以高度为示例,宽度问题可类推.在移动端开发中,经常遇到需要把一块内容定位于底部的情况,当页面内容不满一屏时,需要设为fixed,而超过 一屏时,需要设为static随页面顶到底部,此时就需要 ...

  4. textarea 在光标处插入文字

    效果演示 // 欢迎访问cssfirefly.cnblogs.com html: <textarea id="text" style="width:500px;he ...

  5. php var_export与var_dump 输出的不同

    var_export必须返回合法的php代码,var_export返回的代码,可以直接当作php代码赋值个一个变量. 而这个变量就会取得和被var_export一样的类型的值.   问题描述: 在跟踪 ...

  6. jquery trigger伪造a标签的click事件取代window.open方法

    $(function() { $('#btnyes').click(function () { $('#ssss').attr("href", "http://www.b ...

  7. java之其它命令

    java编译命令 javac: javac -d <目录> 源文件.java 指定存放生成的class文件的路径命令行下编译带包名的java源文件: javac -d . XX.java ...

  8. yabeblog.me 关于Tomcat7部署 一台机器部署两个项目,一个用域名访问,一个用IP访问

    该内容来自 http://www.yabeBlog.me,转载请说明出处. 1.使用IP访问的项目放在Tomcat7 的webapps目录下面:比如:AAA 2.使用域名访问的项目放在Tomcat7的 ...

  9. Error:/etc/fstab:Read-only file system错误的解决办法

    1.挂载60T存储,设置开机自动挂载,UUID编号配置错误导致系统无法启动 2.根据提示进入维护状态,输入root密码,进入fstab删除UUID等内容,结果报错     Error:/etc/fst ...

  10. iOS常见问题(3)

    一.发现不少人在给成员变量初始化的时候,容易进错一个方法去初始化. //注意这个方法只有在内存发生警告的时候才会调用. - (void)didReceiveMemoryWarning { [super ...