congr / world

2 stars 1 forks source link

LeetCode : 682. Baseball Game #443

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/baseball-game/

image image

congr commented 5 years ago

O(N) Stack Println

Your input
["5","-2","4","C","D","9","+","+"]
stdout
[5, -2, -4, 9, 5, 14]
class Solution {
    public int calPoints(String[] ops) {
        Stack<Integer> st = new Stack();

        for (String s: ops) {

            if (s.equals("C")) st.pop();
            else if (s.equals("D")) st.push (st.peek() * 2);
            else if (s.equals("+")) {
                int top = st.pop();
                int val = st.peek() + top;
                st.push(top);
                st.push(val);
            } else {
                st.push(Integer.parseInt(s));
            }
        }

        int sum = 0;
        System.out.println(st);
        for (int i : st) sum += i;
        // while (!st.isEmpty()) sum += st.pop();
        return sum;
    }
}