LeetCode 150. Evaluate Reverse Polish Notation (逆波兰表达式求值)

题目标签:Stack

  利用stack的性质,遍历array,遇到数字就存入stack,遇到运算符号就 从stack pop 出两个数字 计算后 存入回stack,最后返回stack 里的答案。

  

Java Solution: 

Runtime:  24 ms, faster than 5.85% 

Memory Usage: 42.2 MB, less than 6.00 %

完成日期:4/25/2020

关键点:Stack

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> st = new Stack<>();
        
        for(String s : tokens) {
            // if number, push into stack
            if(s.matches("-?\d+")) {
                st.push(Integer.parseInt(s));
            } else {
                // if operator, calculate it and push it into stack
                int b = st.pop(); 
                int a = st.pop();
                
                if(s.equals("+")) 
                    st.push(a + b);
                else if(s.equals("-"))
                    st.push(a - b);
                else if(s.equals("*"))
                    st.push(a * b);
                else if(s.equals("/"))
                    st.push(a / b);
            }
        }
        
        return st.pop();
    }
}

参考资料:n/a

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

原文地址:https://www.cnblogs.com/jimmycheng/p/12776651.html