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 }
标签:String,int,res,words,allowed,字符串,118 From: https://www.cnblogs.com/wzxxhlyl/p/16868616.html