【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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~