精華區beta Marginalman 關於我們 聯絡資訊
https://leetcode.com/problems/count-the-number-of-consistent-strings 1684. Count the Number of Consistent Strings 給一個 由不同字元組成的 allowed 字串 跟一組字串數組 words 數組中的字串 如果所有字元都在 allowed 裡面的話 代表是 consistent 求數組中 consistent 的數量 Example 1: Input: allowed = "ab", words = ["ad","bd","aaab","baa","badab"] Output: 2 Explanation: 只有 "aaab" 跟 "baa" 是由 'a' 和 'b' 組成的 Example 2: Input: allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"] Output: 7 Explanation: 全部字串都是 consistent Example 3: Input: allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"] Output: 4 Explanation: "cc", "acd", "ac" 和 "d" 是 conststent Python Code: class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: a_set = set(allowed) return sum(1 for word in words if all(w in a_set for w in set(word))) allowed 做一次 set 就好 所以多一行 只是這成績真的好爛 :( -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.251.52.67 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1726102106.A.887.html
JerryChungYC: 看了一下all應該也是遇到False就直接跳出 所以就不 09/12 08:49
JerryChungYC: 自己寫for了 09/12 08:49
※ 編輯: JerryChungYC (60.251.52.67 臺灣), 09/12/2024 08:50:53
JerryChungYC: word不轉set好像更好 哀 算了 09/12 08:55
JerryChungYC: count好像比sum好 哀 算了 09/12 08:58
sustainer123: 早早早 09/12 08:59
JerryChungYC: 用-=比用all生成器好 哀 算了 09/12 09:03
class Solution: def countConsistentStrings(self, allowed: str, words: List[str]) -> int: allowed_set = set(allowed) count = 0 for word in words: c = False for w in word: if w not in allowed: c = True break if c: continue count += 1 return count ※ 編輯: JerryChungYC (60.251.52.67 臺灣), 09/12/2024 09:09:16