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