LeetCode——657. Can the robot return to the origin?

Title description:

On the two-dimensional plane, there is a robot starting from the origin (0, 0). Given its moving sequence, judge whether the robot ends at (0, 0) after completing its movement. The order of movement is represented by a character string. The character move[i] represents its i-th move. The effective actions of the robot are R (right), L (left), U (up) and D (down). If the robot returns to the origin after completing all actions, it returns true. Otherwise, it returns false.
Note: The direction the robot "faces" does not matter. "R" will always move the robot to the right once, "L" will always move to the left, etc. In addition, it is assumed that the moving range of the robot is the same each time.

Example 1:

  • Input: "UD"
  • Output: true
  • Explanation: The robot moves up once, and then moves down once. All actions have the same magnitude, so it eventually returns to the origin where it started. Therefore, we return true.

Example 2:

  • Input: "LL"
  • Output: false
  • Explanation: The robot moves to the left twice. It is ultimately located on the left side of the origin, two "movements" from the origin. We return false because it did not return to the origin at the end of the movement.

code show as below:

class Solution {
    
    
    public boolean judgeCircle(String moves) {
    
    
        int n = moves.length();
        int a = 0;
        int b = 0;
        for (int i = 0; i < n; i++) {
    
    
            if (moves.charAt(i) == 'R') {
    
    
                a++;
            } else if (moves.charAt(i) == 'L') {
    
    
                a--;
            }
            if (moves.charAt(i) == 'U') {
    
    
                b++;
            } else if (moves.charAt(i) == 'D') {
    
    
                b--;
            }
        }
        return a == 0 && b == 0;
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114261677