LeetCode_Stack_Evaluate Reverse Polish Notation
来源:互联网 发布:仿淘宝拖拽式模板系统 编辑:程序博客网 时间:2024/06/17 05:28
150. Evaluate Reverse Polish Notation
1. 问题描述:
有一种叫波兰表示法,它是将操作符至于操作数之前,那么这里是反过来,操作数在操作符之前。
输入是String数组,要求输出最后的计算结果。
2. 解决思路:
我们使用stack这种数据结构就很容易实现。栈中存放操作数,碰到操作符,即回去取栈顶的元素计算,结果再放回栈中,最后返回栈顶值即是。这里没有说计算无效或者计算式错误,比如除数为0的情况返回什么,所以就不做特殊处理。
3. java代码:
public class Solution { public int evalRPN(String[] tokens) { Stack<String> stack = new Stack<String>(); for(int i=0;i<tokens.length; i++){ String token = tokens[i]; if(!isOperator(token)){ stack.push(token); } else { int secondNum = Integer.parseInt(stack.pop()); int firstNum = Integer.parseInt(stack.pop()); int curResult = 0; if(token.equals("+")) { curResult = firstNum + secondNum; } else if(token.equals("/")) { if(secondNum==0) curResult = Integer.MAX_VALUE; else curResult = firstNum / secondNum; } else if(token.equals("-")) { curResult = firstNum - secondNum; } else if(token.equals("*")) { curResult = firstNum * secondNum; } stack.push(Integer.toString(curResult)); } } return Integer.parseInt(stack.pop()); } private boolean isOperator(String token){ if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) return true; return false; }}
4. 算法评估:
希望多多指正交流。
0 0
- LeetCode_Stack_Evaluate Reverse Polish Notation
- Reverse Polish Notation
- calculate reverse polish notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- leetcode_Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- java线程
- c语言--基础001--while循环
- 动态修改 NodeJS 程序中的变量值
- 换静态图片---轻开电子商务系统(企业入门级B2C网站)
- 在部署有OGG的数据库主机上打数据库patch遇到的问题libclntsh.so.11.1 active
- LeetCode_Stack_Evaluate Reverse Polish Notation
- 结构体输入输出-指针
- 深入学习Broadcast
- 智力题(第六集)
- 安装VisiBroker出现This Application has Unexpectedly Quit
- XML
- mongodb 学习笔记 08 -- replication复制集
- RS485总线典型电路介绍
- 黑马程序员——Java基础---集合(一)