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

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

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Problem :
    On a 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 movement order 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.
  • Example :
示例 1 :
输入: "UD"
输出: true
解释:机器人向上移动一次,然后向下移动一次。所有动作都具有相同的幅度,因此它最终回到它开始的原点。因此,我们返回 true。
示例 2 :
输入: "LL"
输出: false
解释:机器人向左移动两次。它最终位于原点的左侧,距原点有两次 “移动” 的距离。我们返回 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.
  • Code:
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        U = moves.count('U')
        D = moves.count('D')
        R = moves.count('R')
        L = moves.count('L')
        if U == D and R == L:
            return True
        return False
# 执行用时:36 ms, 在所有 Python3 提交中击败了98.99%的用户
# 内存消耗:13.5 MB, 在所有 Python3 提交中击败了94.54%的用户
  • Algorithm description:
    Abstract the topic into a chessboard pattern, directly count the number of moves in the opposite direction, judge whether they are equal, and return the result.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/108277400