【leetcode】150.(Medium)Evaluate Reverse Polish Notation

解题思路:

使用栈
如果是数字入栈,如果是操作符取出栈中的top两个数字进行操作再将结果入栈


提交代码:

class Solution {
    public int evalRPN(String[] tokens) {
        if(tokens.length==0)	return 0;
        
        Stack<Integer> stack=new Stack<>();
        for(String s: tokens) {
        	if(s.equals("+")) {
        		stack.push(stack.pop()+stack.pop());
        	}else if(s.equals("-")) {
        		stack.push(-1*stack.pop()+stack.pop());
        	}else if(s.equals("*")) {
        		stack.push(stack.pop()*stack.pop());
        	}else if(s.equals("/")) {
        		int num1=stack.pop();
        		int num2=stack.pop();
        		stack.push(num2/num1);
        	}
        	else stack.push(Integer.parseInt(s));
        }
        
        return stack.pop();
    }
}

运行结果:
【leetcode】150.(Medium)Evaluate Reverse Polish Notation