LeetCode--150. Evaluate Reverse Polish Notation

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

要求逆波兰序(Reverse Polish Notation)的四则运算表达式的值,逆波兰序的好处是不像我们手写顺序需要加括号以区分运算优先级,所以逆波兰序形式的运算不易出错,Wikipedia有详细介绍https://en.wikipedia.org/wiki/Reverse_Polish_notation,这里不赘述了。前缀表达式、中缀表达式、后缀表达式的相互转化是计算器计算表达式的核心算法,有时间整理一下它们的相互转换。

本题思路就是借助一个栈,逐个读取四则运算表达式(字符串数组形式)中的字符串对象,遇到数字字符串就入栈,遇到运算符就出栈两个元素进行该运算符的计算,然后将元素按结果入栈,注意这里减法和除法运算符的左右元素顺序,代码如下:

class Solution {
    public int evalRPN(String[] tokens) {
        
        Stack<String> stack=new Stack();
        for(String s:tokens)
        {
            if(s.length()==1)
            {
                char ch=s.charAt(0);
                switch(ch)
                {
                    case '+':
                        {
                            int a=Integer.valueOf(stack.pop());
                            int b=Integer.valueOf(stack.pop());
                            stack.push(String.valueOf(a+b));
                            break;
                        }
                    case '-':
                        {
                            int a=Integer.valueOf(stack.pop());
                            int b=Integer.valueOf(stack.pop());
                            stack.push(String.valueOf(b-a));
                            break;
                        }
                    case '*':
                        {
                            int a=Integer.valueOf(stack.pop());
                            int b=Integer.valueOf(stack.pop());
                            stack.push(String.valueOf(a*b));
                            break;
                        }
                    case '/':
                        {
                            int a=Integer.valueOf(stack.pop());
                            int b=Integer.valueOf(stack.pop());
                            stack.push(String.valueOf(b/a));
                            break;
                        }
                    default:
                        stack.push(s);
                }
            }
            else
                stack.push(s);
        }
        return Integer.valueOf(stack.pop());
    }
}

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/85532432