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

LeetCode 187: Repeated DNA Sequences

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

基本資料
#

難易度: medium 第一次嘗試:2022-11-14

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

解題思路
#

列舉每個長度 10 的子字串(String 模板三,也就是 Sliding Window 模板一的固定視窗),用雜湊表計數(Hash Table 模板一),次數大於 1 的就是答案。

我的嘗試
#

一次 AC。當時迴圈跑到 len(s),尾巴不滿 10 個字元的片段也被放進表裡,但它們各自只出現一次,所以不影響答案。

正確解法
#

class Solution:
    def findRepeatedDnaSequences(self, s: str) -> List[str]:
        cnt = Counter(s[i:i + 10] for i in range(len(s) - 9))
        return [seq for seq, c in cnt.items() if c > 1]

複雜度
#

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

要特別避免的錯誤
#

  • 起點只到 len(s) - 10,不然會把尾巴不滿 10 個字元的片段也算進去。
  • 不能用 s.count(seq):它數的是不重疊的出現次數,"AAAAAAAAAAA" 會漏掉。

面試口說整理
#

我列舉所有長度 10 的子字串放進雜湊表計數,出現超過一次的回傳。每個子字串長度固定是 10,所以時間和空間都是 O(n);想再省可以把 A、C、G、T 編碼成 2 bits,用 rolling hash 讓每次移動 O(1)。

相關文章

LeetCode 424: Longest Repeating Character Replacement
·1 分鐘
LeetCode Medium Hash-Table String Sliding-Window
LeetCode 424 解題筆記:可變長度滑動視窗,視窗長度減掉最多的字元次數就是要替換的數量,超過 k 就縮左邊
LeetCode 208: Implement Trie (Prefix Tree)
·1 分鐘
LeetCode Medium Hash-Table String Design Trie
LeetCode 208 解題筆記:每個節點是 children 字典加一個 is_end 標記;insert、search、startsWith 都是沿著字元往下走
LeetCode 981: Time Based Key-Value Store
·2 分鐘
LeetCode Medium Hash-Table String Binary-Search Design
LeetCode 981 解題筆記:每個 key 存一個 (timestamp, value) 的 list,timestamp 是遞增的;get 時二分找最後一個 timestamp <= 查詢時間的
LeetCode 49: Group Anagrams
·1 分鐘
LeetCode Medium Array Hash-Table String Sorting
LeetCode 49 解題筆記:把每個字串排序後當成 key,同一個 key 的字串就是同一組 anagram
LeetCode 17: Letter Combinations of a Phone Number
·1 分鐘
LeetCode Medium Hash-Table String Backtracking
LeetCode 17 解題筆記:每一層處理一個數字,枚舉它對應的字母;空字串要回傳空 list
LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個