1. 程式人生 > >【LeetCode】657. Robot Return to Origin 解題報告(Python)

【LeetCode】657. Robot Return to Origin 解題報告(Python)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/robot-return-to-origin/description/

題目描述

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.

Example 1:

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

Example 2:

Input: "LL"
Output: false
Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.

題目大意

輸入是機器人移動的方向,每次移動一步。問最終是否出現在出發位置。機器人的面向和移動方向是不想關的。

解題方法

複數求和

Python支援複數運算的,所以指定不同的方向是不同的實數數字就行了。複數的標記是j。最後求和判斷是不是0就是到了原點。

時間複雜度是O(n),空間複雜度是O(1).

class Solution:
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        directs = {'L':-1, 'R':1, 'U':1j, 'D':-1j}
        return 0 == sum(directs[move] for move in moves)

counter統計次數

顯而易見,回到原點的要求是向上走的次數和向下走的次數相等,並且向左和向右走的次數相等。直接字串統計判斷是否哦相等,很快就寫出來。

時間複雜度是O(n),空間複雜度是O(1).

class Solution:
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        count = collections.Counter(moves)
        return count['U'] == count['D'] and count['L'] == count['R']

上面的程式碼也可以直接使用4個變數統計次數,但是時間並沒有明顯提升。

class Solution:
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        u = d = l = r = 0
        for move in moves:
            if move == 'U':
                u += 1
            elif move == "D":
                d += 1
            elif move == 'L':
                l += 1
            elif move == 'R':
                r += 1
        return u == d and l == r

相似題目

參考資料

日期

2018 年 11 月 2 日 —— 渾渾噩噩的一天