leetcode150 Evaluate Reverse Polish Notation
来源:互联网 发布:淘宝达人怎么登录 编辑:程序博客网 时间:2024/05/17 13:12
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
计算逆波兰表达式,使用一个栈来存储操作数字,遍历输入的链表。
如果为数字,直接push到栈内,如果为操作符号,就把栈顶的两个元素pop出来运算一下。
运算的结果push到栈内。
public class Solution { public int evalRPN(String[] tokens) { int result = 0; Stack<Integer> stack = new Stack<Integer>(); String operators = "+-*/"; for(int i=0; i<tokens.length;i++){ if (operators.contains(tokens[i])){ int b = stack.pop(); int a = stack.pop(); stack.push(calculate(a,b,tokens[i])); }else{ stack.push(Integer.valueOf(tokens[i])); } } result = stack.pop(); return result; } public int calculate(int a, int b, String operator){ char op = operator.charAt(0); switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } return 0; }}
0 0
- leetcode150 Evaluate Reverse Polish Notation
- leetcode150 Evaluate Reverse Polish Notation
- leetcode150. Evaluate Reverse Polish Notation
- LeetCode150 Evaluate Reverse Polish Notation java题解
- LeetCode150—Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Runnable和Thread的区别
- C语言单向链表的建立
- Android-transulcent-status-bar总结
- JavaScript中textRange对象使用方法总结(IE only!)
- 自定义系统导航栏UINavigationBarController。
- leetcode150 Evaluate Reverse Polish Notation
- 更改jdk的路径
- git 命令总结
- truncate table drop
- Web---演示Servlet的相关类、表单多参数接收、文件上传简单入门
- JMeter-负载测试
- PAT-B 1046. 划拳
- 求LPS——最长回文子序列
- .NET把小写数字金额转换成大写人民币金额的两种算法