JAVA solution O(n)


  • 0
    Z

    This code costs 11ms for 38 test cases and NOT validates the stack when pop().
    PS: I dont know why use String[] instead of char[] or sth else to save the input.

    class Solution {
    	public int calPoints(String[] ops) {
    		Stack<Integer> score = new Stack<Integer>();
    		for (String op : ops) {
    			if (op.equals("C"))
    				score.pop();
    			else if (op.equals("D"))
    				score.push(score.peek() * 2);
    			else if (op.equals("+")) {
    				int lastNum = score.pop();
    				int sum = lastNum + score.peek();
    				score.push(lastNum);
    				score.push(sum);
    			} else 
    				score.push(Integer.parseInt(op));
    		}
    		int ret = 0;
    		while (!score.empty())
    			ret += score.pop();
    		return ret;
    	}
    }
    

Log in to reply
 

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