TypechoJoeTheme

IT技术分享

统计

[LeetCode 150] Evaluate Reverse Polish Notation [Java]

2017-12-22
/
0 评论
/
752 阅读
/
正在检测是否收录...
12/22

1. Description

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

2. Example

["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

3. Code

import java.util.Stack;

public class LeetCode0150 {
    public int evalRPN(String[] tokens) {
        if(tokens == null || tokens.length == 0) {
            return 0;
        }
        Stack stack = new Stack();
        for(int i = 0; i< tokens.length; i++) {
            String str = tokens[i];
            if(str == " ") {
                continue;
            }
            switch(str) {
            case "+":
                stack.push(stack.pop() + stack.pop());
                break;
            case "-":
                int meiosis = stack.pop();
                stack.push(stack.pop() - meiosis);
                break;
            case "*":
                stack.push(stack.pop() * stack.pop());
                break;
            case "/":
                int divisor = stack.pop();
                stack.push(stack.pop() / divisor);
                break;
            default:
                stack.push(Integer.parseInt(str));
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        LeetCode0150 leetcode = new LeetCode0150();
        String[] tokens = new String[] {"4", "13", "5", "/", "+"};
        System.out.println(leetcode.evalRPN(tokens));
    }
}
Stack
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1313/(转载时请注明本文出处及文章链接)