【LetMeFly】1684.统计一致字符串的数目
力扣题目链接:leetcode.cn/problems/co…
给你一个由不同字符组成的字符串 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 <= 1041 <= allowed.length <= 261 <= words[i].length <= 10allowed中的字符 互不相同 。words[i]和allowed只包含小写英文字母。
方法一:遍历
因为字符集为26个小写英文字母,因此我们开辟大小为的数组,来记录每个字母是否在中出现过
bool bin[26] = {false};
之后遍历一遍,将出现过的字母标记为
for (char& c : allowed)
bin[c - 'a'] = true;
接下来就能愉快地处理每一个字符串了
对于字符串数组中的某一个字符串,使用一个变量来记录字符串是否有“不能出现的字符”
遍历字符串,如果某个字符没有在中出现过(为),那么就将置为并结束遍历这个字符串
若字符串遍历结束仍为,那么答案数量就加一
int ans = 0;
for (string& s : words) { // 遍历字符串数组中的每一个字符串s
bool ok = true;
for (char& c : s) {
if (!bin[c - 'a']) { // 未在allowed中出现过的字符出现过
ok = false;
break;
}
}
ans += ok;
}
- 时间复杂度,其中是中所有字符的个数
- 空间复杂度,其中是字符集大小,这里为26个小写英文字母
AC代码
C++
class Solution {
public:
int countConsistentStrings(string& allowed, vector<string>& words) {
bool bin[26] = {false};
for (char& c : allowed)
bin[c - 'a'] = true;
int ans = 0;
for (string& s : words) {
bool ok = true;
for (char& c : s) {
if (!bin[c - 'a']) {
ok = false;
break;
}
}
ans += ok;
}
return ans;
}
};
同步发文于CSDN,原创不易,转载请附上原文链接哦~ Tisfy:letmefly.blog.csdn.net/article/det…