Weird Java String comparisons


  • 0

    The following solution passed all the test cases.

    class Solution {
        public int calPoints(String[] ops) {
            final Stack<Integer> rounds = new Stack<>();
            for (final String op : ops) {
                if (op.equals("+")) {
                    final int point = rounds.pop() + rounds.peek();
                    rounds.push(point - rounds.peek());
                    rounds.push(point);
                } else if (op.equals("C")) {
                    rounds.pop();
                } else if (op.equals("D")) {
                    rounds.push(2 * rounds.peek());
                } else {
                    rounds.push(Integer.valueOf(op));
                }
            }
            int points = 0;
            for (final int round : rounds) {
                points += round;
            }
            return points;
        }
    }
    

    Then, by changing op.equals("C") to be op == "C", it magically fails with

    Runtime Error Message:
    Line 14: java.lang.NumberFormatException: For input string: "C"
    Last executed input:
    ["5","2","C","D","+"]
    

Log in to reply
 

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