给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。
请你返回 words 数组中 一致字符串 的数目。
【输入】allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
【输出】2
【解释】字符串 "aaab" 和 "baa" 都是一致字符串,因为它们只包含字符 'a' 和 'b' 。
【输入】allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
【输出】7
【解释】所有字符串都是一致的。
【输入】allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
【输出】4
【解释】字符串 "cc","acd","ac" 和 "d" 是一致字符串。
1 <= words.length <= 10^41 <= allowed.length <= 261 <= words[i].length <= 10allowed 中的字符 互不相同 。words[i] 和 allowed 只包含小写英文字母。根据题目描述,我们需要遍历字符串数组words中的每个字符串w,然后针对字符串w的每个字符进行遍历,如果都在allowed中,则称为一致字符串。由于题目要求返回一致字符串的数目,所以当发现w是一致字符串时,数目加1即可。
那么怎么判断字符是否在allowed中呢?我们可以选择Map结构或数组结构来实现。以数组为例,由于英文字母有26个,所以创建一个长度为26的int数组,即:int[] mark = new int[26]; 那么,字符‘a’存储到下标为0的位置,字符‘b’存储到下标为1的位置……。默认mark[i]等于0,遍历allowed字符串中的每个字符,然后将相应字符位置的值赋值为1。这样,就可以在遍历w字符时,快速判断出是否存在于allowed中。
由于思路逻辑很简单,所以,本题就不画图赘述了。
- class Solution {
- public int countConsistentStrings(String allowed, String[] words) {
- int result = 0;
- int[] mark = new int[26];
- for (char ac : allowed.toCharArray()) mark[ac - 'a'] = 1;
- for (String w : words) {
- result++;
- for (char wc : w.toCharArray())
- if (mark[wc - 'a'] == 0) {
- result--;
- break;
- }
- }
- return result;
- }
- }

今天的文章内容就这些了:
写作不易,笔者几个小时甚至数天完成的一篇文章,只愿换来您几秒钟的 点赞 & 分享 。
更多技术干货,欢迎大家关注公众号“爪哇缪斯” ~ \(^o^)/ ~ 「干货分享,每天更新」