↓快轉到主要內容
  1. LeetCode/

LeetCode 657: Robot Return to Origin

·1 分鐘· ·
LeetCode Easy String Simulation
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-29

  • 提交紀錄:Accepted ×3

解題思路
#

上下互相抵消、左右互相抵消,所以只要 U 和 D 的次數相同、L 和 R 的次數相同(Hash Table 計數)。順序不重要。

我的解法
#

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        return moves.count("U") == moves.count("D") and moves.count("L") == moves.count("R")

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • 只看最後的位置,移動的順序不影響答案。

面試口說整理
#

回到原點代表上下互相抵消、左右互相抵消,所以我比較 U 和 D、L 和 R 的次數是否相同。時間 O(n)。

相關文章

LeetCode 415: Add Strings
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 415 解題筆記:兩個指標從尾巴往前逐位相加,記錄進位,迴圈結束後還有進位要補上
LeetCode 412: Fizz Buzz
·1 分鐘
LeetCode Easy Math String Simulation
LeetCode 412 解題筆記:先判斷 15 的倍數,再判斷 5 和 3;倍數要用 %,不是 //
LeetCode 67: Add Binary
·1 分鐘
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 解題筆記:從兩個字串的尾巴往前逐位相加,進位是 sum // 2,這一位是 sum % 2
LeetCode 557: Reverse Words in a String III
·1 分鐘
LeetCode Easy Two-Pointers String
LeetCode 557 解題筆記:用空白切開,每個單字各自反轉,再用空白接回去
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 520: Detect Capital
·1 分鐘
LeetCode Easy String
LeetCode 520 解題筆記:合法的只有三種:全大寫、全小寫、只有第一個字母大寫