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

LeetCode 500: Keyboard Row

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

基本資料
#

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

  • 提交紀錄:Accepted(一次通過)

解題思路
#

三列鍵盤各做成集合(Hash Table),單字轉小寫後的字元集合是其中一列的子集(<=)就能只用那一列打出來。大小寫都算同一個鍵。

我的解法
#

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        rows = [set("qwertyuiop"), set("asdfghjkl"), set("zxcvbnm")]
        return [w for w in words if any(set(w.lower()) <= r for r in rows)]

複雜度
#

時間 O(總字元數),空間 O(1)。

要特別避免的錯誤
#

  • 要先轉小寫再比對。
  • 輸出要保留原本的大小寫和順序。

面試口說整理
#

我把三列鍵盤各做成集合,單字轉小寫後的字元集合如果是某一列的子集就保留,時間是總字元數。

相關文章

LeetCode 349: Intersection of Two Arrays
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 解題筆記:兩個陣列各轉成集合取交集
LeetCode 350: Intersection of Two Arrays II
·1 分鐘
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 解題筆記:保留重複次數的交集,Counter 相交(&)取兩邊次數的較小值
LeetCode 448: Find All Numbers Disappeared in an Array
·1 分鐘
LeetCode Easy Array Hash-Table
LeetCode 448 解題筆記:把陣列本身當雜湊表,看到 x 就把 nums[x - 1] 標成負數,最後還是正數的位置就是沒出現的數
LeetCode 268: Missing Number
·1 分鐘
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 解題筆記:0 到 n 的總和減掉陣列總和就是缺的那個;缺的可能是 0
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小
LeetCode 383: Ransom Note
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 383 解題筆記:ransomNote 每個字元的需求數量都不能超過 magazine 的數量;Counter 相減為空就成立