LeetCode.150 Calculate Reverse Polish Notation
来源:互联网 发布:mysql官方手册中文版 编辑:程序博客网 时间:2024/05/19 23:58
题目:
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
分析:
class Solution { public int evalRPN(String[] tokens) { //实现后缀表达式 //思路:使用stack存储数字,当遇到运算符时,就从stack中取出数字,之后把结果放回stack if(tokens.length==0) return 0; Stack<Integer> stack=new Stack<Integer>(); int firstNum=0,secNum=0; for(int i=0;i<tokens.length;i++){ if(tokens[i].equals("+")){ firstNum=stack.pop(); secNum=stack.pop(); stack.push(firstNum+secNum); }else if(tokens[i].equals("-")){ firstNum=stack.pop(); secNum=stack.pop(); stack.push(secNum-firstNum); }else if(tokens[i].equals("*")){ firstNum=stack.pop(); secNum=stack.pop(); stack.push(firstNum*secNum); }else if(tokens[i].equals("/")){ firstNum=stack.pop(); secNum=stack.pop(); stack.push(secNum/firstNum); }else{ //只是数字,直接入栈 stack.push(Integer.parseInt(tokens[i])); } } return stack.pop(); }}
阅读全文
0 0
- LeetCode.150 Calculate Reverse Polish Notation
- calculate reverse polish notation
- LeetCode 150 Evaluate Reverse Polish Notation
- LeetCode: Evaluate Reverse Polish Notation [150]
- LeetCode(150) Evaluate Reverse Polish Notation
- [leetcode 150] Evaluate Reverse Polish Notation
- [LeetCode 150]Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation - LeetCode 150
- LeetCode---(150)Evaluate Reverse Polish Notation
- [Leetcode 150, Medium] Evaluate Reverse Polish Notation
- leetcode[150]:Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- [leetcode-150]Evaluate Reverse Polish Notation(c++)
- leetcode 150: Evaluate Reverse Polish Notation
- 【leetcode】No.150 Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- LeetCode 150 Evaluate Reverse Polish Notation
- 通信原理之AD转换和PCM编码以及时分复用
- 汇编------中断
- 07 linux内核device-tree基础
- SVM——(六)软间隔目标函数求解
- python django-forbidden-csrf-cookie-not-set问题
- LeetCode.150 Calculate Reverse Polish Notation
- 连接oracle数据库
- 柯南博客——序
- 鼠标悬停整体旋转
- Java 8新特性终极指南
- WEB应用开发从入门到精通系列文章——前言篇
- 任务调度框架Quartz(一) Quartz——一个强大的定时任务调度框架
- Python列表数据复制冒号使用
- 计算机操作系统笔记