C++中计算所有给定句子中都存在的单词数量


我们得到多个以字符串形式表示的句子。目标是计算存在于所有句子中的单词数量。

注意 − 只考虑包含全小写字母的单词

如果句子是:

“我正在学习C语言”

“学习新事物很容易”

“孩子们正在学习健康习惯”

只有“学习”存在于所有三个句子中。所以计数是1。

让我们通过例子来理解

输入 − “衣服是干的”, “所有孩子都在玩”, “那些是最好的日子”

输出 − 存在于所有给定句子中的单词数量为:2

解释 − 单词“the”和“were”存在于所有句子中。

输入 − “我们要去学校”, “如果你愿意,就继续”, “所有这些都卖掉了”

输出 − 存在于所有给定句子中的单词数量为:1

解释 − 单词“are”存在于所有句子中。

下面程序中使用的算法如下

在这个方法中,我们首先将第一个句子的单词存储在vector<pair<string, bool>>集合中。

我们将使用unordered_map<string, bool> check来查找在其他所有句子中都存在的单词。

  • 使用vector<string> vec。并用包含句子的所有字符串初始化它。

  • 句子的数量将是vec.size()。

  • 函数words_sentences(vector<string> vec, int size)接收句子向量和大小,并返回存在于所有给定句子中的单词数量

  • 将初始计数设置为0。

  • 使用临时字符串str来存储句子中的单个单词。

  • 使用while循环遍历存储在vec[0]中的第一个句子。

  • 在其中使用另一个while循环,提取str[]中的单个单词,直到遇到空格。

  • 现在我们在str中有了第一个句子的一个单词,向集合中添加一对(str,true)。

  • 对存储在vec[0]中的句子中的所有单词执行此操作。

  • 向量集合现在包含第一个句子中所有单词与true值的配对。

  • 使用for循环从第二个句子遍历到最后一个句子(j=1到j<size)。

  • 从vec[j]中的当前句子中提取每个单词并存储在str中。

  • 使用check[str]=true在映射check中将这些单词标记为true。

  • 对vec[j]中当前句子中的所有单词执行此操作。

  • 使用for循环遍历向量集合,并对于当前句子查找这些单词是否也在集合中。

  • 再次使用for循环遍历向量集合。

  • 如果当前单词出现在所有句子中,则set[k].second将为true。如果是,则递增计数。

  • 最后,变量count将包含出现在所有句子中的单词。

  • 返回count作为结果。

示例

 在线演示

#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

更新于:2020年12月3日

189 次浏览

开启您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.