Straightforward Java with List


  • 1
    class Solution {
        public int calPoints(String[] ops) {
            int score = 0;
            List<Integer> ls = new ArrayList<Integer>();
            for (int i = 0; i < ops.length; i++) {
                String s = ops[i];
                if (s.equals("+")) {
                	int num = 0;
                	for (int ii = 0, il = ls.size() - 1; ii < 2 && il >= 0; ii++, il--)
                		num += ls.get(il);
                	score += num;
                	ls.add(num);
                } else if (s.equals("C")) {
                	int num = ls.get(ls.size() - 1);
                	score -= num;
                	ls.remove(ls.size() - 1);
                } else if (s.equals("D")) {
                	int num = ls.get(ls.size() - 1) * 2;
                	score += num;
                	ls.add(num);
                } else {
                	int num = Integer.valueOf(s);
                	score += num;
                	ls.add(num);
                }
            }
            return score;
        }
    }
    

  • 0
    W

    My approach.

    public int calPoints(String[] ops) {
        int ans = 0;
        Stack<Integer> stk = new Stack<>();
        for (String op : ops) {
            if (op.equals("C")) { ans -= stk.pop (); continue; }
            else if (op.equals ("D")) stk.push (stk.peek () * 2);
            else if (op.equals ("+")) stk.push (stk.get(stk.size () - 1) + stk.get(stk.size () - 2));
            else stk.push (Integer.valueOf (op));
            ans += stk.peek(); 
        }
        return ans;
    }
    

Log in to reply
 

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