Share my concise stack solution


  • 0
    S
    public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
    	for (String s : tokens) {
    		if (Character.isDigit(s.charAt(0)) || s.length()>1){
    			stack.push(Integer.parseInt(s));
    		}else {
    			int n2 = stack.pop(), n1 = stack.pop();
    			if (s.equals("+")) stack.push(n1+n2);
    			else if (s.equals("-"))stack.push(n1-n2);
    			else if (s.equals("*")) stack.push(n1*n2);
    			else if (s.equals("/")) stack.push(n1/n2);
    		}
    	}
    	return stack.peek();
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.