Leetcode Evaluate Reverse Polish Notation

来源:互联网 发布:t-sql语法基础知识 编辑:程序博客网 时间:2024/04/30 14:31

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

Difficulty: Medium


Solution: Use stack to implement. Two useful fuction: Integer.valueOf, String.valueOf.


public class Solution {    public int evalRPN(String[] tokens) {        String oper = "+-*/";        Stack<String> sta = new Stack<String>();        for(String temp : tokens){            if(!oper.contains(temp)){                sta.push(temp);            }            else{                int num1 = Integer.valueOf(sta.pop());                int num2 = Integer.valueOf(sta.pop());                if(temp.equals("+")){                    sta.push(String.valueOf(num2 + num1));                }                if(temp.equals("-")){                    sta.push(String.valueOf(num2 - num1));                }                if(temp.equals("*")){                    sta.push(String.valueOf(num2 * num1));                }                if(temp.equals("/")){                    sta.push(String.valueOf(num2 / num1));                }            }        }        return Integer.valueOf(sta.pop());            }}




0 0