【118】

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 class Solution {
 2     public int countConsistentStrings(String allowed, String[] words) {
 3         StringBuilder pattern = new StringBuilder();
 4         pattern.append("[");
 5         for(int i = 0; i < allowed.length(); i++){
 6             pattern.append(allowed.charAt(i));
 7         }
 8         pattern.append("]");
 9         String pattern1 = pattern.toString();
10         int res = 0;
11         for(String word : words){
12             if(word.matches(pattern1) == true){
13                 res++;
14             }
15         }
16         return res;
17     }
18 }
复制代码

 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

使用遍历暴力求解

复制代码
 1 class Solution {
 2     public int countConsistentStrings(String allowed, String[] words) {
 3         int res = words.length;
 4         for(int i = 0; i < words.length; i++){
 5             for(char ch : words[i].toCharArray()){
 6                 if(!allowed.contains(String.valueOf(ch))){//匹配到一个不包含的就跳出循环
 7                     res--;
 8                     break;
 9                 }
10             }
11         }
12         return res;
13     }
14 }
复制代码

 

posted @   Wianxhlyl  阅读(128)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示