「每日LeetCode」2021年3月16日

本文最后更新于:2023年3月19日 晚上

Lt1684. 统计一致字符串的数目

1684. 统计一致字符串的数目

给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串  **。
请你返回 words 数组中 **一致字符串
的数目。
示例 1:

1
2
3
输入:allowed = "ab", words = ["ad","bd","aaab","baa","badab"]
输出:2
解释:字符串 "aaab""baa" 都是一致字符串,因为它们只包含字符 'a''b'

示例 2:

1
2
3
输入:allowed = "abc", words = ["a","b","c","ab","ac","bc","abc"]
输出:7
解释:所有字符串都是一致的。

示例 3:

1
2
3
输入:allowed = "cad", words = ["cc","acd","b","ba","bac","bad","ac","d"]
输出:4
解释:字符串 "cc""acd""ac""d" 是一致字符串。

提示:

  • 1 <= words.length <= 10
  • 1 <= allowed.length <=26
  • 1 <= words[i].length <= 10
  • allowed 中的字符 互不相同
  • words[i]allowed 只包含小写英文字母。

思路

用一个 set 记录 allowed 中的字符,遍历每一个单词,再遍历每一个单词中的字符,如果都在 set 中就计数加一。最后返回符合要求的字符数量。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
var countConsistentStrings = function (allowed, words) {
const allowedSet = new Set(allowed.split(""));
let res = 0;
for (const word of words) {
let flag = true;
for (const char of word) {
if (!allowedSet.has(char)) {
flag = false;
break;
}
}
if (flag) res++;
}
return res;
};