題目
給你一個由不同字符組成的字符串 allowed 和一個字符串?dāng)?shù)組 words 。如果一個字符串的每一個字符都在 allowed 中,就稱這個字符串是 一致字符串 。
請你返回 words 數(shù)組中 一致字符串 的數(shù)目。
示例 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 只包含小寫英文字母。
解題思路
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
res = 0
## 通過Set方式來進行判斷抽取,復(fù)雜度降低
allowedSet = set(allowed)
for word in words:
wordSet = set(word)
if wordSet.issubset(allowedSet):
res += 1
# res += 1
# for i in wordSet:
# if i not in allowedSet:
# res -= 1
# break
return res
if __name__ == '__main__':
# allowed = "ab"
# words = ["ad","bd","aaab","baa","badab"]
allowed = "abc"
words = ["a", "b", "c", "ab", "ac", "bc", "abc"]
ret = Solution().countConsistentStrings(allowed, words)
print(ret)