150. Evaluate Reverse Polish Notation - LeetCode

Question

150. Evaluate Reverse Polish Notationjava

Solution

2 1 + 3 * ((2+1)*3)的後綴(postfix)或逆波蘭(reverse Polish)記法,計算這個表達式容易想到棧,當見到一個數時就入棧,見到操做符時該運算符做用於從該棧中彈出的兩個數上,將所得結果入棧。git

public int evalRPN(String[] tokens) {
    Stack<Integer> stack = new Stack<>();
    for (String tmp : tokens) {
        if (tmp.length() > 1) {
            stack.push(Integer.parseInt(tmp));
            continue;
        }
        char c = tmp.charAt(0); // String轉char
        int a, b;
        switch (c) {
            case '+':
                b = stack.pop();
                a = stack.pop();
                stack.push(a + b);
                break;
            case '-':
                b = stack.pop();
                a = stack.pop();
                stack.push(a - b);
                break;
            case '*':
                b = stack.pop();
                a = stack.pop();
                stack.push(a * b);
                break;
            case '/':
                b = stack.pop();
                a = stack.pop();
                stack.push(a / b);
                break;
            default:
                stack.push(c - '0'); // char 轉 int
        }
    }
    return stack.pop();
}

Reference

相關文章
相關標籤/搜索