Leetcode 682

2820 단어
// Line 25: error: cannot find symbol: method parseInt()
/* Exception in thread "main" java.util.EmptyStackException
    at java.util.Stack.peek(Stack.java:59)
    at Solution.calPoints(Solution.java:19)
    at __DriverSolution__.__helper__(__Driver__.java:8)
    at __Driver__.main(__Driver__.java:52)
*/

class Solution {
    public int calPoints(String[] ops) {
        if (ops == null) return 0;
        Stack stack = new Stack();
        int sum = 0;
        for (int i = 0; i < ops.length; i++) {
            if (ops[i].equals("C")) {
                if(stack.size() != 0) {
                    int lastRound = stack.pop();
                    sum -= lastRound;
                }
            } else if (ops[i].equals("D")) {
                // need to check the size of stack?
                int lastRound = stack.peek();
                sum += 2*lastRound;
            } else if (ops[i].equals("+")) {
                if (stack.size() != 0) {
                    int last1 = stack.pop();
                    int last2 = stack.peek();
                    stack.push(last1);
                    sum += (last1 + last2);
                }
                
            } else {
                int score = ops[i].parseInt();
                stack.push(score);
                sum += score;
            }
        }
        return sum;
    }
}

// Wrong answer
// didn't understand the question clearly

class Solution {
    public int calPoints(String[] ops) {
        if (ops == null) return 0;
        Stack stack = new Stack();
        int sum = 0;
        for (int i = 0; i < ops.length; i++) {
            if (ops[i].equals("C")) {
                if(stack.size() != 0) {
                    int lastRound = stack.pop();
                    sum -= lastRound;
                }
            } else if (ops[i].equals("D")) {
                // need to check the size of stack?
                if (stack.size() != 0) {
                    int lastRound = stack.peek();
                    stack.push(2*lastRound);
                    sum += 2*lastRound;
                }
                
            } else if (ops[i].equals("+")) {
                if (stack.size() > 1) {
                    int last1 = stack.pop();
                    int last2 = stack.peek();
                    stack.push(last1);
                    stack.push(last1 + last2);
                    sum += (last1 + last2);
                }
                
            } else {
                int score = Integer.parseInt(ops[i]);
                stack.push(score);
                sum += score;
            }
        }
        return sum;
    }
}

좋은 웹페이지 즐겨찾기