原文链接: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
- class Solution {
- public int countConsistentStrings(String allowed, String[] words) {
- Set
set = new HashSet<>(); - //将allowed中每一个字符存入set
- for(int i=0;i
- set.add(allowed.charAt(i));
- }
- int res=0;//记录结果
- for(String word : words){
- int ans = 0;//标志位
- char[] ch = word.toCharArray();
- for(char temp : ch){
- //判断每一个字符是否存在set中
- if(!set.contains(temp)){
- //遇到不存在的,退出循环
- ans = 0;
- break;
- }
- //所有字符都存在,标志位为1
- ans=1;
- }
- //当标志位为1时,表明是一致字符串
- if(ans==1) res++;
- }
- return res;
- }
- }
优化
将set改为数组去存放allowed
时间:6ms 空间:42.4MB
- class Solution {
- public int countConsistentStrings(String allowed, String[] words) {
- int[] allow=new int[26];
- for(int i=0;i
- allow[allowed.charAt(i)-'a']=1;
- }
- int res = 0;
- for(String word : words){
- int ans=0;
- for(char temp : word.toCharArray()){
- if(allow[temp-'a']==0){
- ans=0;
- break;
- }
- ans=1;
- }
- if(ans==1)res++;
- }
- return res;
- }
- }
-
相关阅读:
低代码平台选型宝典:避免弯路,轻松选对适合你的平台
零售业的技术演变:远程支持软件的作用
二维数组的定义和初始化
阿里云视频点播介绍
.Net CLR GC 动态加载短暂堆阈值的计算及阈值超量的计算
Perl5和Perl6对比使用Sigils的差别
Java 面试题:如何保证集合是线程安全的? ConcurrentHashMap 如何实现高效地线程安全?
非对称渐开线齿轮学习笔记分享
离散傅里叶变换(DFT)和基2快速傅里叶变换(FFT)算法的C语言实现
Ubuntu22.04 安装配置VNC Server
-
原文地址:https://blog.csdn.net/qq_52726736/article/details/127764815