224/227/772/150 Basic Calculator 1 2 3 and Evaluate Reverse Polish Notation

1. https://leetcode.com/problems/basic-calculator/description/

2. https://leetcode.com/problems/basic-calculator-ii/description/

3. https://leetcode.com/problems/basic-calculator-iii/description/

4. https://leetcode.com/problems/evaluate-reverse-polish-notation/description/

150. Evaluate Reverse Polish Notation

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation: 
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
简单题,用一个stack 去模拟就可以了,遇到数字push stack, 遇到 操作符 pop 两次 进行计算。
class Solution {
    public int evalRPN(String[] tokens) {
        
        Stack<String> stack = new Stack<>();
        
        for(String str: tokens){
            if(!isOperator(str)) {
                stack.push(str);
            }   
            
            else {
                int num2 = Integer.valueOf(stack.pop());
                int num1 = Integer.valueOf(stack.pop());
                int res = cal(num1,num2,str);
                stack.push(String.valueOf(res));
            }
        } 
        return Integer.valueOf(stack.pop());  
    }
    
    private boolean isOperator(String str){
        if(str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) return true;
        return false;
    }
    
    private int cal(int n1, int n2, String op){
        if(op.equals("+")) return n1+n2;
        else if(op.equals("-")) return n1-n2;
        else if(op.equals("*")) return n1*n2;
        else return n1/n2;
    }
}

224. Basic Calculator  

只有 () 和 + -, 求字符表达式的 值。

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23


猜你喜欢

转载自www.cnblogs.com/keepAC/p/9912938.html