• Leetcode1684:统计一致字符串的数目


    原文链接:1684. 统计一致字符串的数目 - 力扣(LeetCode)


    题目

            给你一个由不同字符组成的字符串 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 只包含小写英文字母。

    解题思路

    1、把allowed字符串全部存入set集合
    2、取出words中的每一个字符串word
    3、查看word中的每一个字符是否存在与set集合中

    时间:12ms 空间:42MB

    1. class Solution {
    2.     public int countConsistentStrings(String allowed, String[] words) {
    3.         Set set = new HashSet<>();
    4.         //将allowed中每一个字符存入set
    5.         for(int i=0;i
    6.             set.add(allowed.charAt(i));
    7.         }
    8.         int res=0;//记录结果
    9.         for(String word : words){
    10.             int ans = 0;//标志位
    11.             char[] ch = word.toCharArray();
    12.             for(char temp : ch){
    13.                 //判断每一个字符是否存在set中
    14.                 if(!set.contains(temp)){
    15.                     //遇到不存在的,退出循环
    16.                     ans = 0;
    17.                     break;
    18.                 }
    19.                 //所有字符都存在,标志位为1
    20.                 ans=1;
    21.             }
    22.             //当标志位为1时,表明是一致字符串
    23.             if(ans==1) res++;
    24.         }
    25.         return res;
    26.     }
    27. }

    优化
    将set改为数组去存放allowed

    时间:6ms 空间:42.4MB

    1. class Solution {
    2.     public int countConsistentStrings(String allowed, String[] words) {
    3.         int[] allow=new int[26];
    4.         for(int i=0;i
    5.             allow[allowed.charAt(i)-'a']=1;
    6.         }
    7.         int res = 0;
    8.         for(String word : words){
    9.             int ans=0;
    10.             for(char temp : word.toCharArray()){
    11.                 if(allow[temp-'a']==0){
    12.                     ans=0;
    13.                     break;
    14.                 }
    15.                 ans=1;
    16.             }
    17.             if(ans==1)res++;
    18.         }
    19.         return res;
    20.     }
    21. }
  • 相关阅读:
    “Spark+Hive”在DPU环境下的性能测评 | OLAP数据库引擎选型白皮书(24版)DPU部分节选
    kafka消息重复消费解决方案
    14:00面试,14:06就出来了,问的问题有点变态。。。。。。
    基于Conda的PyTorch Geometric报“段错误 (核心已转储)”的解决方法
    盘点30个Python树莓派源码Python爱好者不容错过
    《逆向工程核心原理》学习笔记(六):高级逆向分析技术
    【无标题】
    [ 红队知识库 ] 常见防火墙(WAF)拦截页面
    【工具】idea 设置自动渲染注释
    【面试】JVM垃圾回收
  • 原文地址:https://blog.csdn.net/qq_52726736/article/details/127764815