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

LeetCode 3120: Count the Number of Special Characters I

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

基本資料
#

難易度: easy 第一次嘗試:2024-04-21

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

解題思路
#

把出現過的字母分成兩個集合:小寫出現過的、大寫出現過的(都轉成同一種大小寫存),兩邊都有的字母就是 special,答案是交集的大小(Hash Table)。

我的解法
#

class Solution:
    def numberOfSpecialChars(self, word: str) -> int:
        lower = {c for c in word if c.islower()}
        upper = {c.lower() for c in word if c.isupper()}
        return len(lower & upper)

複雜度
#

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

要特別避免的錯誤
#

  • 兩個集合要轉成同一種大小寫才能取交集。

面試口說整理
#

我把小寫出現過的字母和大寫出現過的字母各放一個集合,轉成同樣的大小寫後取交集,大小就是答案。時間 O(n)。

相關文章

LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 804: Unique Morse Code Words
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 804 解題筆記:把每個單字轉成摩斯碼字串,放進集合後算有幾種
LeetCode 500: Keyboard Row
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 500 解題筆記:鍵盤的三列各做成集合,單字轉小寫後的字元集合是某一列的子集就保留
LeetCode 13: Roman to Integer
·1 分鐘
LeetCode Easy Hash-Table Math String
LeetCode 13 解題筆記:從左到右加每個符號的值,如果它比右邊的符號小就改成減
LeetCode 1189: Maximum Number of Balloons
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 1189 解題筆記:每個字母可以組幾個 balloon 是 次數 // 需要數,l 和 o 需要兩個,取最小值
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開