LeetCode | Evaluate Reverse Polish Notation
来源:互联网 发布:数据库关联 编辑:程序博客网 时间:2024/04/29 17:56
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
后缀表达式,用栈做,遇到运算符出栈两个元素做运算,然后把结果入栈。switch(“字符串”)是jdk1.7的新特性。
代码如下:public class Solution { public int evalRPN(String[] tokens) { int temp = 0; MyStack ms = new MyStack(); for(int i=0; i<tokens.length; i++){ switch(tokens[i]){ case "+": temp = ms.pop() + ms.pop(); ms.push(temp);break; case "-": temp = -ms.pop() + ms.pop(); ms.push(temp);break; case "*": temp = ms.pop() * ms.pop(); ms.push(temp);break; case "/": temp = ms.pop();temp = ms.pop() / temp; ms.push(temp);break; default: temp = Integer.parseInt(tokens[i]); ms.push(temp); } } return ms.pop(); }}class MyStack{ int[] stack = new int[1000000]; int top = 1; int pop(){ if(top == 0) return 0; top--; return stack[top]; } void push(int a){ if(top > stack.length) return; stack[top] = a; top++; }}
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
- 《生死疲劳》
- 求3个数字的平均值而且保留到小数点后3位
- 【UML】概述以及面向对象技术总结
- 编辑文章 - 博客频道 - CSDN.NET
- 如何建立一棵哈夫曼树并且输出压缩码
- LeetCode | Evaluate Reverse Polish Notation
- Android之开发性能优化简介
- hdu 5002 Tree
- Spring3 mvc hello world demo
- UML关系(泛化,实现,依赖,关联(聚合,组合))
- [Android笔记]HandelThread使用
- Android App 内存泄露之Handler
- ZOJ 3209 Treasure Map (Dancing Links 精确覆盖 )
- 关于 ubuntu 12.04 无法使用QQ的问题