不包含给定字符串的任何字符的字符串计数
给定一个包含N个字符串的数组arr和一个字符串str ,任务是找出不包含字符串str的任何字符的字符串的数量。
例子:
Input: arr[] = {“abcd”, “hijk”, “xyz”, “ayt”}, str=”apple”
Output: 2
Explanation: “hijk” and “xyz” are the strings that do not contain any character of str
Input: arr[] = {“apple”, “banana”, “pear”}, str=”nil”
Output: 1
方法:按照以下步骤解决此问题:
- 创建一个集合st并将字符串str 的每个字符存储在该集合中。
- 创建一个变量ans来存储所有需要的字符串的数量。
- 现在,开始遍历数组,对于每个字符串,检查它的任何字符是否存在于集合 st 中。如果是,那么这不是必需的字符串。
- 如果它不包含集合中的任何字符,则将答案增加 1。
- 循环结束后返回ans ,作为这个问题的答案。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to count the number of strings
// that does not contain any character of string str
int allowedStrings(vector& arr, string str)
{
int ans = 0;
unordered_set st;
for (auto x : str) {
st.insert(x);
}
for (auto x : arr) {
bool allowed = 1;
for (auto y : x) {
// If the character is present in st
if (st.find(y) != st.end()) {
allowed = 0;
break;
}
}
// If the string doesn't
// have any character of st
if (allowed) {
ans += 1;
}
}
return ans;
}
// Driver Code
int main()
{
vector arr
= { "abcd", "hijk", "xyz", "ayt" };
string str = "apple";
cout << allowedStrings(arr, str);
}
Python3
# Python 3 code for the above approach
# Function to count the number of strings
# that does not contain any character of string str
def allowedStrings(arr, st):
ans = 0
st1 = set([])
for x in st:
st1.add(x)
for x in arr:
allowed = 1
for y in x:
# If the character is present in st1
if (y in st1):
allowed = 0
break
# If the string doesn't
# have any character of st
if (allowed):
ans += 1
return ans
# Driver Code
if __name__ == "__main__":
arr = ["abcd", "hijk", "xyz", "ayt"]
st = "apple"
print(allowedStrings(arr, st))
# This code is contributed by ukasp.
Javascript
输出
2
时间复杂度: O(N*M),其中 N 是数组的大小,M 是最长字符串的大小。
辅助空间: O(N)