150. Evaluate Reverse Polish Notation (M)

来源:互联网 发布:淘宝退货售后怎么删除 编辑:程序博客网 时间:2024/06/07 14:15

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

Subscribe to see which companies asked this question

My naive Solution:

public class Solution {    public int evalRPN(String[] tokens) {        int re=0;        CharSequence operator="+-*/";        Stack<Integer> data=new Stack<Integer>();        for(String i:tokens){            if(i.equals("+")||i.equals("-")||i.equals("*")||i.equals("/")){                int n2=data.pop();                int n1=data.pop();                int temp=0;                char oper=i.charAt(0);                switch(oper){                    case('+'):                        temp=n1+n2;                        break;                    case('-'):                        temp=n1-n2;                        break;                    case('*'):                        temp=n1*n2;                        break;                    case('/'):                        temp=n1/n2;                        break;                        default:                        break;                }                data.push(temp);            }            else                data.push(Integer.valueOf(i));        }        return data.pop();    }}

Cleaner:

public class Solution {    public int evalRPN(String[] tokens) {        Stack<Integer> data=new Stack<Integer>();        for(String i:tokens){            switch(i){                case("+"):                    data.push(data.pop()+data.pop());                    break;                case("-"):                    data.push(-data.pop()+data.pop());                    break;                case("*"):                    data.push(data.pop()*data.pop());                    break;                case("/"):                    int n2=data.pop();                    int n1=data.pop();                    data.push(n1/n2);                    break;                default:                    data.push(Integer.valueOf(i));                    break;            }        }        return data.pop();    }}


0 0
原创粉丝点击