Evaluate Reverse Polish Notation, Leetcode 解题笔记

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应用,遇到数字push,遇到符号pop并计算。

public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> s = new Stack<Integer>();
        int opd1 = 0, opd2 = 0;
        for(String str: tokens){
            if(str.equals("+")){
                opd1 = s.pop();
                opd2 = s.pop();
                s.push(opd2 + opd1);
            }
            else if(str.equals("-")){
                opd1 = s.pop();
                opd2 = s.pop();
                s.push(opd2 - opd1);
            }
            else if(str.equals("*")){
                opd1 = s.pop();
                opd2 = s.pop();
                s.push(opd2 * opd1);
            }
            else if(str.equals("/")){
                opd1 = s.pop();
                opd2 = s.pop();
                s.push(opd2 / opd1);
            }
            else{
                s.push(Integer.parseInt(str));
            }
        }
        return s.pop();
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s