0%

『LeetCode』1684 统计一致字符串的数目

题目

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 <= words.length <= 10^{4}
  • 1 <= allowed.length <=^{ }26
  • 1 <= words[i].length <= 10
  • allowed 中的字符 互不相同 。
  • words[i] 和 allowed 只包含小写英文字母。

标签

位运算, 数组, 哈希表, 字符串


题解

【统计一致字符串的数目】简单哈希模拟

逐字符串逐字符判断即可,可以用哈希表存一下 allowed 加速判断

1
2
3
4
# Code language: Python
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
return sum(all(s in st for s in w) for w in words) if (st := set(allowed)) else 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Code language: Java
class Solution {
public int countConsistentStrings(String allowed, String[] words) {
int cnt = 0;
boolean[] st = new boolean[27];
for (int i = 0, n = allowed.length(); i < n; ++i) st[allowed.charAt(i) - 'a'] = true;
out: for (String w: words) {
for (int i = 0, n = w.length(); i < n; ++i) {
if (!st[w.charAt(i) - 'a']) continue out;
}
++cnt;
}
return cnt;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Code language: C++
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
int cnt = 0;
bool st[27]{false};
for (int i = 0, n = allowed.size(); i < n; ++i) st[allowed[i] - 'a'] = true;
for (string &w: words) {
bool tag = true;
for (int i = 0, n = w.size(); i < n; ++i) {
if (!st[w[i] - 'a']) tag = false;
if (!tag) break;
}
if (tag) ++cnt;
}
return cnt;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* Code language: JavaScript */
/**
* @param {string} allowed
* @param {string[]} words
* @return {number}
*/
var countConsistentStrings = function(allowed, words) {
const st = new Map();
let cnt = 0;
for (let s of allowed) st[s] = true;
for (let w of words) {
let tag = true;
for (let s of w) {
if (!st[s]) tag = false;
if (!tag) break;
}
if (tag) cnt++;
}
return cnt;
};
  • 时间复杂度: \(O(\sum_{w \in words} len(w))\)
  • 空间复杂度: \(O(26)\), 哈希表最多有 26 个字符

如果对你有帮助的话,请给我点个赞吧~

欢迎前往 我的博客Algorithm - Github 查看更多题解

--- ♥ end ♥ ---

欢迎关注我呀~