zeqing-guo / algorithms-study

MIT License
0 stars 1 forks source link

Leetcode-150: Evaluate Reverse Polish Notation #100

Open zeqing-guo opened 8 years ago

zeqing-guo commented 8 years ago

Description

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

My Solution

代码的 run time 是13 ms (96.97%)。时间复杂度是O(n),空间复杂度是O(n)

public class Solution {
    public int evalRPN(String[] tokens) {
        LinkedList<Integer> ll = new LinkedList<>();

        for (int i = 0; i < tokens.length; ++i) {
            int value = 0;
            String token = tokens[i];
            char head = token.charAt(0);
            if ((head == '+' || head == '-' || head == '*' || head == '/') && token.length() == 1) {
                int num1 = ll.pop();
                int num2 = ll.pop();
                switch (head) {
                    case '+': value = num2 + num1; break;
                    case '-': value = num2 - num1; break;
                    case '*': value = num2 * num1; break;
                    case '/': value = num2 / num1; break;
                    default: value = 0;
                }
                ll.push(value);
            } else {
                ll.push(Integer.valueOf(token));
            }
        }

        return ll.remove();
    }
}

Analysis

从左往右扫一遍,将结果保存在stack里,简单题。