Leetcode 657. Robot Return to Origin
You are given a string moves that represents the movements of a robot on a 2D plane. The robot starts at the origin (0, 0) and each character in the string represents a move:
Determine if the robot returns to the origin after completing all of its moves. Return true if it returns to the origin, otherwise return false.
moves?
moves can range from 1 to 2 * 10^4.moves contain only the characters ‘U’, ‘D’, ‘L’, ‘R’?
x and y initialized to 0, representing the current position of the robot.moves string and update the coordinates accordingly:
y by 1.y by 1.x by 1.x by 1.x and y are 0. If they are, return true; otherwise, return false.public class Solution {
public boolean judgeCircle(String moves) {
int x = 0;
int y = 0;
for (char move : moves.toCharArray()) {
switch (move) {
case 'U':
y++;
break;
case 'D':
y--;
break;
case 'L':
x--;
break;
case 'R':
x++;
break;
}
}
return x == 0 && y == 0;
}
}
moves. We only need to traverse the string once to determine the final position.With this approach, we efficiently determine if the robot returns to the origin after completing the series of moves.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?