LeetCode 150. Evaluate Reverse Polish Notation(java)

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
这道题在解法思路上没有什么问题,用stack预存前两个数,每次遇到一个operator就从stack中pop出两个数计算,再塞回去,但是有很多比较tricky的点,比如:1. stack有可能为空,无法pop出数据,我们的解决方法就是抛出IllegalArgumentException。2. 从stack中pop出数字进行运算的时候要把第二个pop出的数据当做被运算数,同时要注意除法的时候除数不为0。3. 栈中的数字可能为负数,因此我们在自己写isDigit函数的时候要记住第一个字符可以是‘-’,但是不能只有一个‘-’字符。
public int evalRPN(String[] tokens) {
        //special case
        if (tokens == null) return -1;
        if (tokens.length == 1) {
            return Integer.parseInt(tokens[0]);
        }
        if (tokens.length < 3) return -1;
        //general case
        Stack<Integer> stack = new Stack<>();
        for (String s : tokens) {
            if (s == null || s == "") return -1;
            if (isDigit(s)) {
                stack.push(Integer.parseInt(s));
            } else {
                try {
                    int num1 = stack.pop();
                    int num2 = stack.pop();
                    int num = 0;
                    if (s.equals("+")) {
                        num = num1 + num2;
                    } else if (s.equals("-")) {
                        num = num2 - num1;
                    } else if (s.equals("*")) {
                        num = num1 * num2;
                    } else if (s.equals("/")) {
                        if (num1 == 0) return -1;
                        num = num2 / num1;
                    }
                    stack.push(num);
                } catch (IllegalArgumentException e) {
                    return -1;
                }
            }
        }
        if (stack.isEmpty()) return -1;
        else {
            int res = stack.pop();
            return res;
        } 
    }
    public boolean isDigit(String s) {
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(0) == '-') {
                if (s.length() == 1) return false;
                else continue;
            }
            char c = s.charAt(i);
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
阅读更多
换一批

Polish notation

05-16

Problem DescriptionnReverse Polish notation (RPN) is a method for representing expressions in which the operator symbol is placed after the arguments being operated on. nPolish notation, in which the operator comes before the operands, was invented in the 1920s by the Polish mathematician Jan Lucasiewicz. nIn the late 1950s, Australian philosopher and computer scientist Charles L. Hamblin suggested placing the operator after the operands and hence created reverse polish notation. nnRPN has the property that brackets are not required to represent the order of evaluation or grouping of the terms. nRPN expressions are simply evaluated from left to right and this greatly simplifies the computation of the expression within computer programs. nAs an example, the arithmetic expression (3+4)*5 can be expressed in RPN as 3 4 + 5 *. nnReverse Polish notation, also known as postfix notation, contrasts with the infix notation of standard arithmetic expressions in which the operator symbol appears between the operands. So Polish notation just as prefix notation.nnNow, give you a string of standard arithmetic expressions, please tell me the Polish notation and the value of expressions.n nnInputnThere're have multi-case. Every case put in one line, the expressions just contain some positive integers(all less than 100, the number of integers less than 20), bi-operand operators(only have 3 kinds : +,-,*) and some brackets'(',')'.nyou can assume the expressions was valid.n nnOutputnEach case output the Polish notation in first line, and the result of expressions was output in second line.nall of the answers are no any spaces and blank line.the answer will be not exceed the 64-signed integer.n nnSample Inputn1+2-3*(4-5)n1+2*(3-4)-5*6n nnSample OutputnCase 1:n- + 1 2 * 3 - 4 5n6nCase 2:n- + 1 * 2 - 3 4 * 5 6n-31

没有更多推荐了,返回首页