LintCode:M-逆波兰表达式求值
来源:互联网 发布:李晨璐 数据 编辑:程序博客网 时间:2024/05/17 03:45
LintCode链接
求逆波兰表达式的值。
在逆波兰表达法中,其有效的运算符号包括 +
, -
, *
, /
。每个运算对象可以是整数,也可以是另一个逆波兰计数表达。
样例
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
标签
题目其实就是语法树后序遍历的结果
TC = O(n)
SC = O(m),m表示叶子数目,即数字的个数,当左子树全是数字,栈的SC值达到最大
public class Solution { /* * @param tokens: The Reverse Polish Notation * @return: the value */ public int evalRPN(String[] tokens) { // write your code here Stack<Integer> stack = new Stack<Integer>(); int n = tokens.length; //double res=0; for(int i=0; i<n; i++){ String s = tokens[i]; if(s.charAt(s.length()-1)>='0' && s.charAt(s.length()-1)<='9'){ stack.push(Integer.valueOf(s)); }else{ Integer b = stack.pop(); Integer a = stack.pop(); switch(s.charAt(0)){ case '*': stack.push(a*b); break; case '+': stack.push(a+b); break; case '-': stack.push(a-b); break; case '/': stack.push(a/b); break; } } } return stack.pop(); }}
阅读全文
0 0
- LintCode:M-逆波兰表达式求值
- LintCode : 逆波兰表达式求值
- LintCode:逆波兰表达式求值
- Lintcode 逆波兰表达式求值
- lintcode--逆波兰表达式求值
- Lintcode 逆波兰表达式求值
- 逆波兰表达式求值-LintCode
- lintcode-逆波兰表达式求值-424
- LintCode 424-逆波兰表达式求值
- lintcode-逆波兰表达式求值-424
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- 逆波兰表达式求值
- poj 2739
- HDU1274 展开字符串
- 深入理解Java对象的创建过程:类的初始化与实例化
- MySQL约束及相关操作
- CCF 火车购票(Java)
- LintCode:M-逆波兰表达式求值
- ACM算法:快速幂取模(详细)
- PHP 开发者该知道的 5 个 Composer 小技巧
- 关于技术团队的建设
- spring之JDBC
- 网络通信概述
- 黑盒测试和白盒测试
- java 在主程序中添加和引用自定义程序的两种方法(主类中的static方法和其他类中的普通方法)
- NI PXIE6259接线说明