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

LeetCode 383: Ransom Note

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

基本資料
#

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

  • 提交紀錄:Wrong Answer → Accepted ×3

解題思路
#

數 magazine 每個字元有幾個(Hash Table 模板一),再扣掉 ransomNote 需要的,任何一個不夠就失敗。Python 的 Counter(a) - Counter(b) 只保留正數,所以結果是空的就代表每個字元都夠。

我的嘗試
#

第一版回傳 bool(Counter(ransomNote) - Counter(magazine)),意思剛好相反:差集不是空的代表不夠,例如 "a"、"c" 回傳 True。改成 not 就 AC 了。

正確解法
#

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        return not (Counter(ransomNote) - Counter(magazine))

複雜度
#

時間 O(n + m),空間 O(k)。

要特別避免的錯誤
#

  • Counter 相減「不是空的」代表不夠,要回傳 not ...,不是 bool(...)。

面試口說整理
#

我把 ransomNote 的字元次數減掉 magazine 的字元次數,Counter 相減只留下正數,結果是空的就代表每個字元都夠。時間 O(n + m)。

相關文章

LeetCode 387: First Unique Character in a String
·1 分鐘
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 解題筆記:先計數,再從左到右找第一個次數是 1 的字元
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小
LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個
LeetCode 409: Longest Palindrome
·1 分鐘
LeetCode Easy Hash-Table String Greedy
LeetCode 409 解題筆記:每個字元取偶數個放兩邊,只要有任何奇數次的字元,中間還能再放一個
LeetCode 242: Valid Anagram
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 242 解題筆記:兩個字串的字元次數完全相同就是 anagram,用 Counter 比較或排序後比較
LeetCode 205: Isomorphic Strings
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 205 解題筆記:兩個字串的字元要一對一對應,字元種類數和配對種類數都相同就成立