• LeetCode每日一题——1684. 统计一致字符串的数目


    LeetCode每日一题系列

    题目: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 只包含小写英文字母。

    思路

    先将allowed中的所有字符存入集合set中,在依次遍历words中每一个字符串,判断字符串中的所有字符是否都存在于set中,若全部存在,则符合条件,答案加一。统计所有情况返回结果即可。

    题解

    class Solution:
        def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
            tmp, ans = set(), 0
            # 存入set备用
            for i in range(len(allowed)):
                tmp.add(allowed[i])
            # 遍历字符串数组
            for i in words:
                judge = True
                # 判断每一个字符是否都在set中
                for j in range(len(i)):
                    if i[j] not in tmp:
                        judge = False
                        break
                if judge:
                    ans += 1
            return ans
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    动态生成表格完整版(内含解析)
    ABAP 长文本操作
    Spring事务的传播行为
    SpringBoot 整合 MongoDB 实战解说
    基于web的客车自动收费系统
    SpringBoot SpringBoot 开发实用篇 4 数据层解决方案 4.13 ES 下载与安装
    Django--31Django知识体系梳理总结
    DataX更新null值到ElasticSearch不生效的问题
    设计模式-行为型-解释器模式
    新零售O2O 电商模式解析
  • 原文地址:https://blog.csdn.net/m0_52000372/article/details/127744555