0

Link:https://leetcode.com/problems/robot-return-to-origin/

Question: There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

You are given a string moves that represents the move sequence of the robot where moves[i] represents its ith move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).

Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.

My approach was to make a haskmap that record how many times the U, D, L, and R moves occured in the string. If the number of U equals the number the D and the number of L equals the number of R, we return true since it means that the robot would be back at the origin. Else, we return false. I'm confused why my code only worked for some testcases when I used == to compare the number of each letter. If I change == to .equals, my code passes all the testcases. Why is this the case? Since we are comparing integer objects, shouldn't both == and .equals just check if the memory locations are the same? Here is my code (the commented code is what I had initially):

class Solution {
public boolean judgeCircle(String moves) {
    HashMap<Character,Integer> map = new HashMap<Character,Integer>();
    char[] move=moves.toCharArray();
    map.put('R',0);
    map.put('L',0);
    map.put('U',0);
    map.put('D',0);
    for (char i : move){
        if(!map.containsKey(i)) return false;
        map.put(i,map.get(i)+1);
    }
    if(map.get('R').equals(map.get('L'))&&map.get('U').equals(map.get('D'))){
        return true;
    }
    /*
    if(map.get('R')==map.get('L')&&map.get('U')==map.get('D')){
        return true;
    }
    */
    return false;
}

}

  • 2
    `Integer` is an object type, not a primitive type. Integers in the range -128, 127 might be cached, and then `==` happens to work. When comparing object, you should always use `equals` (unless you want to check object identity). – Mark Rotteveel Apr 09 '23 at 09:10

0 Answers0