Title: Can the robot return to the origin
The movement order is represented by a string. The character move[I] indicates its i-th move. The effective actions of the robot are R (right), L (left), U (up) and D (down). Returns true if the robot returns to the origin after completing all actions. Otherwise, return false. Note: It doesn't matter which way the robot is "facing". "R" will always make the robot move to the right once, "L" will always move to the left, etc. Furthermore, assume that the robot moves by the same amount each time it moves.Copy the code
Example:
Input: "UD" Output: true Explanation: The robot moves up once, then down once. All actions have the same magnitude, so it eventually returns to where it started. Therefore, we return true. Input: "LL" Output: false Explanation: Robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it does not return to the origin at the end of the move.Copy the code
Think about:
This problem just counts the number of occurrences of four characters in a string. As long as R and L have the same number of occurrences, and U and D have the same number of occurrences, the robot can return to the origin.Copy the code
Implementation:
class Solution { public boolean judgeCircle(String moves) { int r_count = 0; int l_count = 0; int u_count = 0; int d_count = 0; char[] charArray = moves.toCharArray(); for (int count = 0; count < moves.length(); count++) { if (charArray[count] == 'R') { r_count++; } else if (charArray[count] == 'L') { l_count++; } else if (charArray[count] == 'D') { d_count++; } else if (charArray[count] == 'U') { u_count++; } } if (r_count == l_count && u_count == d_count) { return true; } else { return false; }}}Copy the code