1684. 統計一緻字元串的數目
給你一個由不同字元組成的字元串
allowed
和一個字元串數組
words
。如果一個字元串的每一個字元都在
allowed
中,就稱這個字元串是 一緻字元串 。
請你傳回
words
數組中 一緻字元串 的數目。
示例 1:
輸入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
輸出:2
解釋:字元串 "aaab" 和 "baa" 都是一緻字元串,因為它們隻包含字元 'a' 和 'b' 。
示例 2:
輸入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
輸出:7
解釋:所有字元串都是一緻的。
示例 3:
輸入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
輸出:4
解釋:字元串 "cc","acd","ac" 和 "d" 是一緻字元串。
-
1 <= words.length <= 104
-
1 <= allowed.length <= 26
-
1 <= words[i].length <= 10
-
中的字元 互不相同 。allowed
-
和 words[i]
隻包含小寫英文字母。allowed
Solution
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
cnt = len(words)
for word in words:
for letter in word:
if letter not in allowed:
cnt -= 1
break
return cnt
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
mask = 0
for c in allowed:
mask |= 1 << (ord(c) - ord('a'))
res = 0
for word in words:
mask1 = 0
for c in word:
mask1 |= 1 << (ord(c) - ord('a'))
res += (mask1 | mask) == mask
return res
作者:力扣官方題解
連結:https://leetcode.cn/problems/count-the-number-of-consistent-strings/solutions/1953831/tong-ji-yi-zhi-zi-fu-chuan-de-shu-mu-by-38356/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。