leetcode(150):Evaluate Reverse Polish Notation
2016-08-13 13:43
441 查看
原题:
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
分析:题意为计算逆波兰表达式的值,用stack很好解决,直接上代码:
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
分析:题意为计算逆波兰表达式的值,用stack很好解决,直接上代码:
public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> st = new Stack<Integer>(); for (String s:tokens) { if(s.equals("+")) { st.push(st.pop()+st.pop()); } else if(s.equals("-")) { int a =st.pop(); int b = st.pop(); st.push(b-a); } else if(s.equals("*")) { st.push(st.pop()*st.pop()); } else if(s.equals("/")) { int a = st.pop(); int b = st.pop(); st.push(b/a); } else{ st.push(Integer.parseInt(s)); } } return st.pop(); } }
相关文章推荐
- [leetcode-150]Evaluate Reverse Polish Notation(c++)
- [leetcode 150] Evaluate Reverse Polish Notation
- 【LeetCode】150 Evaluate Reverse Polish Notation 小侃小解
- LeetCode150 Evaluate Reverse Polish Notation
- LeetCode150:Evaluate Reverse Polish Notation
- Leetcode 150 Evaluate Reverse Polish Notation 反向波兰表示法求值
- leetcode150 Evaluate Reverse Polish Notation
- LeetCode 150 Evaluate Reverse Polish Notation
- 【LeetCode-面试算法经典-Java实现】【150-Evaluate Reverse Polish Notation(计算逆波兰式)】
- LeetCode(150) Evaluate Reverse Polish Notation
- leetcode150 Evaluate Reverse Polish Notation
- LeetCode - 150 - Evaluate Reverse Polish Notation
- leetcode[150]Evaluate Reverse Polish Notation
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- leetcode[150]:Evaluate Reverse Polish Notation
- leetcode-150-Evaluate Reverse Polish Notation
- leetcode 150 —— Evaluate Reverse Polish Notation
- leetcode[150] Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation(计算逆波兰表达式) --java实现
- [LeetCode 150] Evaluate Reverse Polish Notation