Simple C++ solution


  • 0
    T

    You just need two counters to solve this problem. One counter x which denotes the distance in the X coordinate, and the other counter y which denotes the distance in the Y coordinate. Then you loop the string when you find a U, increase x by 1, and when you find a D decrease x by 1, similarly for y. Eventually, if both x and y are equal to 0, that means the robot makes a circle. The time complexity is O(N).

    public:
        bool judgeCircle(string moves) {
            int x = 0;
            int y = 0;
            for (int i = 0; i < moves.length(); ++i) {
                if (moves[i] == 'U')
                    ++y;
                else if (moves[i] == 'D')
                    --y;
                else if (moves[i] == 'R')
                    ++x;
                else if (moves[i] == 'L')
                    --x;
            }
            
            return ((x == 0) && (y == 0));
        }
    };```

Log in to reply
 

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