Share my concise stack solution

  • 0
    public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
    	for (String s : tokens) {
    		if (Character.isDigit(s.charAt(0)) || s.length()>1){
    		}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.