题目

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

样例

["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. win10任务视图

    之所以用到win10任务视图源自于一个需求,就是我想在上班操作电脑的同时想将某个游戏在后台挂机,这样工作归工作,挂机归挂机,互不干扰.win10任务视图就能轻松的解决这个问题. 任务视图 新建任务视图 ...

  2. 封装鼠标滚轮事件_mousewheel

    function mousewheel(obj,fn){ obj.onmousewheel===null ? obj.onmousewheel=fun : obj.addEventListener(' ...

  3. laravel--为什么属性在模型中没有定义,却取出来了值,这些属性哪里来的

    看laravel模型中的这段代码, public function getLimitUsersAttribute() { return $this->user_limit - $this-> ...

  4. Asp.net MVC Global.asax文件

    global.asax文件概述 global.asax这个文件包含全局应用程序事件的事件处理程序.它响应应用程序级别和会话级别事件的代码. 运行时, Global.asax 将被编译成一个动态生成的 ...

  5. 初级jQuery的使用

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  6. Nginx+uWSGI+Django原理

    Python的Web开发中,如果使用Django框架,那么较为成熟稳定的服务器架构一般是Nginx+uWSGI+Django.而为什么一定要三个结合在一起呢?直接使用Django的runserver来 ...

  7. Oracle 的证也会过期咯

    How does this recertification requirement affect me? If your Database Certification credential is re ...

  8. 世界级Oracle专家Jonathan Lewis:我很为DBA们的未来担心(图灵访谈)

    部分节选 图灵社区:如果您的子女对计算机科学感兴趣,你会让他们选什么具体的方向呢? JL:我的孩子对计算机科学一点都不感兴趣,甚至对科学都没什么兴趣.他们主修的都是艺术.如果要我给其他的人建议的话,我 ...

  9. windows下SSH客户端远程访问Linux出现错误

  10. C++中的虚函数(类的向上转换,和向下转换)

    1.C++中的封装时为了代码的模块化,继承是为了代码的重用,而多态则是为了接口的重用. 2.C++中的多态是用虚函数来实现的. 3.子类对象向父类指针的转换(向上转换)是安全的,隐式的,而父类对象向子 ...