LeetCode 150. Evaluate Reverse Polish Notation

来源:互联网 发布:hyper v配置nat网络 编辑:程序博客网 时间:2024/06/07 03:30

题目链接:https://leetcode.com/problems/evaluate-reverse-polish-notation/

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

基本解题思路

1.先Wiki百科下:

Reverse Polish notation也就是逆波兰表示法,是一种是由波兰数学家扬·武卡谢维奇1920年引入的数学表达式方式,在逆波兰记法中,所有操作符置于操作数的后面,因此也被称为后缀表示法。逆波兰结构由弗里德里希·鲍尔(Friedrich L. Bauer)和艾兹格·迪科斯彻在1960年代早期提议用于表达式求值,以利用堆栈结构减少计算机内存访问。

2.逆波兰表达式的解释器:

逆波兰表达式的解释器一般是基于堆栈的。解释过程一般是:操作数入栈;遇到操作符时,操作数出栈,求值,将结果入栈;当一遍后,栈顶就是表达式的值。因此逆波兰表达式的求值使用堆栈结构很容易实现,并且能很快求值。


提交代码:

第一次提交的基础版本:

使用stack作为堆栈,stack_top指向栈顶;然后从前往后遍历tokens,函数OpOrNum用于判断token是数字还是操作符,遇到数字则加入堆栈中,遇到操作符则使用medi_result集合栈顶数字和栈顶后一个数字计算出中间结果,并加入堆栈;最后遍历结束,栈顶数字即最终结果

public class Solution {    public int evalRPN(String[] tokens) {        if (tokens.length == 1) { // 排除不需要计算的情况return Integer.parseInt(tokens[0]);}        int[] stack = new int[tokens.length];        stack[0] = Integer.parseInt(tokens[0]);        stack[1] = Integer.parseInt(tokens[1]);        int stack_top = 2;        for (int i = 2; i < stack.length; i++) {if (OpOrNum(tokens[i])) {int a = stack[stack_top-2];int b = stack[stack_top-1];stack[stack_top-2] = medi_result(tokens[i], a, b);stack_top=stack_top-1;}else {stack[stack_top] = Integer.parseInt(tokens[i]);stack_top++;}}        return stack[0];    }         public boolean OpOrNum(String token) {if (token.equals("+")|token.equals("-")|token.equals("*")|token.equals("/")) {System.out.println(token);return true;}return false;}        public int medi_result(String token, int a, int b){    int result = 0;    if (token.equals("+")) {result = a+b;}    if (token.equals("-")) {    result = a-b;}    if (token.equals("*")) {    result = a*b;}    if (token.equals("/")&&(b!=0)) {    result = a/b;}    return result;    }}

优化版本(下次更新):

to be continued....

0 0
原创粉丝点击