LeetCode 1684. 統(tǒng)計一致字符串的數(shù)目

題目

給你一個由不同字符組成的字符串 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)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容