题目
给你一个由不同字符组成的字符串 allowed
和一个字符串数组 words
。如果一个字符串的每一个字符都在 allowed
中,就称这个字符串是 一致字符串 。
请你返回 words
数组中 一致字符串 的数目。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-the-number-of-consistent-strings
题目著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
- 枚举所有的
words[i]
- 判断
allowed
,words[i]
是否符合条件,函数bool in(...)
;
时间复杂度
O(n*len(word)*len(allowed))
空间复杂度
O(1)
代码
class Solution {
public:
bool in(string str2, string str1) {
for(auto c : str1) {// 枚举words[i]中的每个字符
if(str2.find(c) == string::npos) return false; // 如果没找到find会返回string::npos
}
return true;
}
int countConsistentStrings(string allowed, vector<string>& words) {
int ans = 0;
for(auto str : words) {
ans += in(allowed, str); // 符合条件+1,
}
return ans;
}
};