Evaluate Reverse Polish Notation
2016-07-17 20:10
477 查看
Evaluate the value of an arithmetic expression in Reverse Polish Notation.Valid operators are
+,
-,
*,
/. Each operand may be an integer or another expression.Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 Analysis: Use a stack to save the numbers, once an operator is found, pop two numbers from stack, and push the result back to stack. Note: make sure the order of the operands.
public class Solution { /** * @param tokens The Reverse Polish Notation * @return the value */ public int evalRPN(String[] tokens) { if (tokens == null || tokens.length == 0) return 0; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < tokens.length; i++) { if (!(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/"))) { stack.push(Integer.parseInt(tokens[i])); } else { if (stack.size() < 2) return 0; int value1 = stack.pop(); int value2 = stack.pop(); if (tokens[i].equals("+")) { stack.push(value1 + value2); } else if (tokens[i].equals("-")) { stack.push(value2 - value1); } else if (tokens[i].equals("*")) { stack.push(value1 * value2); } else { if (value1 == 0) { return Integer.MAX_VALUE; } stack.push(value2 / value1); } } } return stack.pop(); } }
相关文章推荐
- evaluate-reverse-polish-notation
- ulua(一)上手
- 《Lua程序设计》第2章 类型与值 学习笔记
- 《Lua程序设计》第1章 开始 学习笔记
- Lua中的注释
- Lua学习笔记 入门的两个小程序
- Leetcode-evaluate-reverse-polish-notation
- Lua教程(四):在Lua中调用C语言、C++的函数
- Lua教程(二):C++和Lua相互传递数据示例
- Lua教程(三):C语言、C++中调用Lua的Table示例
- Lua教程(五):C/C++操作Lua数组和字符串示例
- 和我一起写lua - C和lua的参数传递与返回值
- lua-string-resty的aes加密解密,无法和python的aes进行对接
- ulua经验
- ulua使用经验
- Lua类继承的优雅实现方式
- ulua热更新小demo
- C++11 lambda表达式 实际上是lua的闭包方式
- Lua基础[持续更新]
- ubuntu 下安装lua语言