LeetCode 657 Robot Return to Origin 解题报告

题目要求

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.

Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

题目分析及思路

题目给出一个机器人的移动序列,若能返回原点则返回true,否则返回false。可以设定水平和垂直两个方向上的计数,若移动之后仍保持方位的不变,则返回到了原点。

python代码​

class Solution:

    def judgeCircle(self, moves):

        """

        :type moves: str

        :rtype: bool

        """

        vertical = 0

        horizontal = 0

        for move in moves:

            if move == 'R':

                horizontal+=1

            elif move == 'L':

                horizontal-=1

            elif move == 'U':

                vertical+=1

            else:

                vertical-=1

        return horizontal == 0 and vertical == 0

            

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10237164.html