Leetcode Evaluate Reverse Polish Notation
来源:互联网 发布:t-sql语法基础知识 编辑:程序博客网 时间:2024/04/30 14:31
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
Difficulty: Medium
Solution: Use stack to implement. Two useful fuction: Integer.valueOf, String.valueOf.
public class Solution { public int evalRPN(String[] tokens) { String oper = "+-*/"; Stack<String> sta = new Stack<String>(); for(String temp : tokens){ if(!oper.contains(temp)){ sta.push(temp); } else{ int num1 = Integer.valueOf(sta.pop()); int num2 = Integer.valueOf(sta.pop()); if(temp.equals("+")){ sta.push(String.valueOf(num2 + num1)); } if(temp.equals("-")){ sta.push(String.valueOf(num2 - num1)); } if(temp.equals("*")){ sta.push(String.valueOf(num2 * num1)); } if(temp.equals("/")){ sta.push(String.valueOf(num2 / num1)); } } } return Integer.valueOf(sta.pop()); }}
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
- 插入排序
- leetcode之Integer Break
- 有关Android多屏幕适配的问题
- 《JavaScript学习笔记》:Ajax的应用
- 《CSS权威指南》学习记录——颜色和背景
- Leetcode Evaluate Reverse Polish Notation
- 递归排序
- Ubuntu软件安装
- 《剑指offer》:[25]二叉树中和为某一值的路径
- linux 6.5下 MySQL 5.6 RPM安装
- 选择排序法
- BIOS/UEFI基础——第一条指令
- Leetcode Paint House
- POJ 3974 Palindrome manacher