1. 程式人生 > >LeetCode 657 Robot Return to Origin 解題報告

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