Evaluate Reverse Polish Notation

原创 2015年07月09日 18:14:38
public class Solution {
    public int evalRPN(String[] tokens) {
        if (tokens == null || tokens.length == 0) {
            return Integer.MAX_VALUE;
        }
        int result = 0;
        Stack<String> stack = new Stack<String>();
        for (String s : tokens) {
            if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
                int second = Integer.parseInt(stack.pop());
                int first = Integer.parseInt(stack.pop());
                if (s.equals("+")) {
                    stack.push(String.valueOf(first + second));
                } else if (s.equals("-")) {
                    stack.push(String.valueOf(first - second));
                } else if (s.equals("*")) {
                    stack.push(String.valueOf(first * second));
                } else if (s.equals("/")) {
                    stack.push(String.valueOf(first / second));
                }
            } else {
                stack.push(s);
            }
        }
        return Integer.parseInt(stack.pop());   
    }
}

相关文章推荐

【算法】Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -...

LeetCode–Evaluate Reverse Polish Notation

LeetCode–Evaluate Reverse Polish Notation (LeetCode - 评价逆波兰表示法,即后缀表达式) By X Wang (LeetCode: 一个在线编...

[leetcode]Evaluate Reverse Polish Notation题解

描述 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are ...

[C++]LeetCode: 98 Evaluate Reverse Polish Notation

题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators...

(leetcode)Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation 题目 Evaluate the value of an arithmetic expression in Reverse Pol...
  • fcunren
  • fcunren
  • 2014年08月18日 15:28
  • 278

leetcode笔记:Evaluate Reverse Polish Notation(逆波兰式的计算)

该题考查逆波兰式,也叫后缀表达式(将运算符写在操作数之后)。假设有一个表达式E,其后缀形式定义如下: 1. 如果E是一个变量或常量,则E的后缀式是E本身; 2. 如果E是E1 operator E...

LeetCode 150. Evaluate Reverse Polish Notation

LeetCode 150. Evaluate Reverse Polish Notation 栈

LeetCode|Evaluate Reverse Polish Notation

题目 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are ...
  • hwb1992
  • hwb1992
  • 2014年04月20日 21:26
  • 603

LeetCode:《Evaluate Reverse Polish Notation》

#include #include #include #include using namespace std; class Solution { public: int evalRP...

150.Evaluate Reverse Polish Notation(Stack-Medium)

转载请注明作者和出处:http://blog.csdn.net/c406495762
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Evaluate Reverse Polish Notation
举报原因:
原因补充:

(最多只允许输入30个字)