我们以字符串形式给出了多个句子。目的是计算所有句子中存在的单词数。
注意-包含所有小写字母的单词将仅被考虑
如果句子是-
“我正在学习C语言”
“学习新事物很容易”
“孩子们正在学习健康的习惯”
这三者中只有“学习”。因此计数为1。
让我们用例子来理解
输入-“衣服干了”,“所有孩子都在玩”,“那是最好的日子”
输出-所有给定句子中存在的单词数为-2
说明-所有句子中都出现单词“ the”和“ were”。
输入-“我们要去学校”,“如果您愿意然后继续”,“所有这些都卖了”
输出-所有给定句子中存在的单词数为-1
说明-所有句子中都出现单词“ are”。
在这种方法中,我们将首先将第一句话的单词存储在vector <pair <string,bool >>集中。
我们将使用unordered_map <string,bool>检查在所有其他句子的向量集中找到单词。
取一个vector <string> vec。并使用所有包含句子的字符串对其进行初始化。
句子数为vec.size()。
函数words_sentences(vector <string> vec,int size)获取句子和大小的向量,并返回所有给定句子中存在的单词数
将初始计数设为0。
使用临时字符串str将单个单词存储在句子中。
使用while循环遍历存储在vec [0]中的第一句话。
在其中使用另一个while循环,在str []中提取单个单词,直到遇到空间。
现在我们有了str中第一个句子的单词,将一对(str,true)添加到集合中。
对存储在vec [0]中的句子中的所有单词执行此操作。
向量集现在具有成对的第一个句子的所有单词,其值为真。
使用从j = 1到j <size的for循环,从第二个句子到最后一个句子的遍历向量。
从vec [j]中的当前句子中提取每个单词,并存储在str中。
在映射检查中使用check [str] = true将这些单词标记为true。
对vec [j]中当前句子中的所有单词执行此操作。
使用for循环,遍历向量集和当前句子查找是否检查中的这些单词也位于集合中。
使用for循环,再次遍历向量集。
如果当前单词出现在所有句子中,则set [k] .second将为true。如果是,则增加计数。
最后,我们将对所有句子中出现的单词进行计数。
返回计数作为结果。
#include <bits/stdc++.h>
using namespace std;
int words_sentences(vector<string> vec, int size){
int count = 0;
int i = 0;
string str;
unordered_map<string, bool> check;
vector<pair<string, bool>> set ;
pair<string, bool> str_bool;
while (i < vec[0].size()){
str = "";
while (i < vec[0].size() && vec[0][i] != ' '){
str += vec[0][i];
i++;
}
i++;
if (str != ""){
str_bool = make_pair(str, true);
set.push_back(str_bool);
}
}
for (int j = 1; j < size; j++){
check.clear();
i = 0;
while (i < vec[j].size()){
str = "";
while (i < vec[j].size() && vec[j][i] != ' '){
str += vec[j][i];
i++;
}
i++;
if (str != ""){
check[str] = true;
}
}
for(int k = 0; k < set.size(); k++){
if (set[k].second != false && check[set[k].first] == false){
set[k].second = false;
}
else if (set[k].second != false && check[set[k].first] == true){
check[set[k].first] = false;
}
}
}
for (int k = 0; k < set.size(); k++){
if (set[k].second == true){
count++;
}
}
return count;
}
int main(){
vector<string> vec;
vec.push_back("Honesty is the best policy");
vec.push_back("policy varies from company to company");
vec.push_back("Employee should follow the policy of a company");
int size = vec.size();
cout<<"Count of words that are present in all the given sentences are: "<<words_sentences(vec, size);
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Count of words that are present in all the given sentences are: 1