给定N个字符串列表,任务是找到不是任何其他给定列表的子列表的列表的计数。
例子:
Input: [[“hey”, “hi”, “hello”], [“hey”, “bye”], [“hey”, “hi”]]
Output: 2
Explaination
The third list is a subset of the first list, hence the first and the second list are the required lists.
Input: [[“geeksforgeeks”, “geeks”], [“geeks”, “geeksforgeeks”]]
Output: 0
Explanation: Both the lists comprise of same set of strings.
方法
请按照以下步骤解决问题:
- 首先,枚举所有向量中所有可能的字符串,即给它们分配一个整数。
- 然后,对所有单独的列表使用一个 Bitset 来存储它们中存在的字符串。
- 比较位集。如果其中一个位集是另一个的子集,则忽略该列表。否则,在集合中插入该列表的索引。
- 打印集合中的所有索引。
下面的代码是上述方法的实现:
C++
// C++ program to find all lists
// which are not a subset of any
// other given lists
#include
using namespace std;
#define N 50005
// Function to print all lists which
// are not a subset of any other lists
void findNonSubsets(vector >& v,
vector& ans)
{
unordered_map mp;
int id = 1;
// Enumerate all strings
// present in all lists
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v[i].size(); j++) {
if (mp.count(v[i][j]) > 0)
continue;
mp[v[i][j]] = id++;
}
}
// Compute and store bitsets
// of all strings in lists
vector > v1;
for (int i = 0; i < v.size(); i++) {
bitset b;
for (int j = 0; j < v[i].size(); j++) {
b[mp[v[i][j]]] = 1;
}
v1.push_back(b);
}
for (int i = 0; i < v.size(); i++) {
bool flag = false;
for (int j = 0; !flag and j < v.size(); j++) {
if (i != j) {
// If one of the bitsets is
// a subset of another, the
// logical AND is equal to the
// subset(intersection operation)
if ((v1[i] & v1[j]) == v1[i]) {
flag = true;
}
}
}
if (!flag) {
ans.push_back(i);
}
}
return;
}
// Driver Program
signed main()
{
vector > v
= { { "hey", "hello", "hi" },
{ "hey", "bye" },
{ "hey", "hi" } };
vector ans;
findNonSubsets(v, ans);
if (ans.size() == 0) {
cout << -1 << endl;
return 0;
}
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
return 0;
}
输出:
0 1
时间复杂度: O ( N * M )
辅助空间: O ( N * M )
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live