150. Evaluate Reverse Polish Notation

Link

Solution

用stack紀錄最近可以用的運算子,每次遇到運算元就pop出兩個來用

    public int evalRPN(String[] tokens) {
        Stack<Integer> s = new Stack<>();
        for(int i = 0; i < tokens.length; i++){
            if(tokens[i].equals("/")){
                int a = s.pop();
                int b = s.pop();
                int c = b/a;
                s.push(c);
            }
            else if(tokens[i].equals("+")){
                int a = s.pop();
                int b = s.pop();
                int c = b+a;
                s.push(c);
            }
            else if(tokens[i].equals("-")){
                int a = s.pop();
                int b = s.pop();
                int c = b-a;
                s.push(c);
            }
            else if(tokens[i].equals("*")){
                int a = s.pop();
                int b = s.pop();
                int c = b*a;
                s.push(c);
            }
            else{
                s.push(Integer.parseInt(tokens[i]));
            }
        }
        return s.peek();
    }

Last updated

Was this helpful?