LeetCode150.逆波兰表达式求值(Java实现)

链接:https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/

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

 

你可能感兴趣的:(LeetCode编程题)