0
点赞
收藏
分享

微信扫一扫

逆波兰表达式求值-150-[中等]

阿尚青子自由写作人 2022-03-19 阅读 74
leetcode

逆波兰表达式:

逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。

  • 平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。
  • 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。

逆波兰表达式主要有以下两个优点:

  • 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
  • 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
package com.company.myQueue;

import java.util.Stack;

public class Solution5 {
    /**
     * 输入:tokens = ["4","13","5","/","+"]
     * 输出:6
     * 解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
     */
    public int evalRPN(String[] tokens) {

        Stack<String> stack = new Stack<>();
        int n = tokens.length;

        for (int i = 0; i < n; i++) {
            if (stack.size() < 2) {
                stack.push(tokens[i]);
            } else {
                if (tokens[i].equals("+")) {
                    int x = Integer.parseInt(stack.pop());
                    int y = Integer.parseInt(stack.pop());
                    stack.push(String.valueOf(x + y));
                } else if (tokens[i].equals("-")) {
                    int x = Integer.parseInt(stack.pop());
                    int y = Integer.parseInt(stack.pop());
                    stack.push(String.valueOf(y - x));
                } else if (tokens[i].equals("*")) {
                    int x = Integer.parseInt(stack.pop());
                    int y = Integer.parseInt(stack.pop());
                    stack.push(String.valueOf(y * x));
                } else if (tokens[i].equals("/")) {
                    int x = Integer.parseInt(stack.pop());
                    int y = Integer.parseInt(stack.pop());
                    stack.push(String.valueOf(y / x));
                } else {
                    stack.push(tokens[i]);
                }
            }

        }
        return Integer.parseInt(stack.pop());
    }
}

力扣icon-default.png?t=M276https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/solution/dong-hua-yan-shi-150-ni-bo-lan-biao-da-s-try7/ 

举报

相关推荐

0 条评论