【LeetCode】Evaluate Reverse Polish Notation
来源:互联网 发布:新疆买买提网络用语 编辑:程序博客网 时间:2024/05/18 21:05
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
2.判断String是否为数字:(1)使用正则表达式 (2)通过Integer.parseInt( )抛异常来判断
import java.util.*;public class Solution { public static int evalRPN(String[] tokens) { Vector<Integer> stack = new Vector<Integer>(); int len = tokens.length; for(int i = 0;i< len;i++) { boolean isNum = tokens[i].matches("-?[0-9]+"); if(isNum) { int tmp = Integer.parseInt(tokens[i]); stack.addElement(tmp); } else { int length = stack.size(); int tmp1 = stack.elementAt(length-2); int tmp2 = stack.elementAt(length-1); stack.removeElementAt(length-1); stack.removeElementAt(length-2); if(tokens[i].equals("+")) { int sum = tmp1 + tmp2; stack.addElement(sum); } else if(tokens[i].equals("-")) { int sub = tmp1 - tmp2; stack.addElement(sub); } else if(tokens[i].equals("*")) { int mul = tmp1 * tmp2; stack.addElement(mul); } else if(tokens[i].equals("/")) { int dive = tmp1/tmp2; stack.addElement(dive); } else { } } } int result = stack.elementAt(0); return result; } }
0 0
- Evaluate Reverse Polish Notation | leetcode
- leetcode-Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Leetcode: Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Leetcode:Evaluate Reverse Polish Notation
- Zabbix 2.4.0 安装、配置
- 黑马程序员——java核心类库
- javascript全解析
- java文件上传
- Android文件操作
- 【LeetCode】Evaluate Reverse Polish Notation
- ps压缩图片
- Mybatis入门
- linux系统中如何查看日志 (常用命令)
- deviceready事件
- cmd环境使用代理
- mkdir
- 图片上传前预览
- 可穿戴设备之父—阿莱克斯•彭特兰(Alex Pentland)