在 C++ 中查找字符串中的第一个重复单词


在本篇报告中,我们得到了一个包含逗号分隔单词的字符串 str。我们的任务是找到字符串中的第一个重复单词

我们需要找到字符串中的第一个单词(两个空格之间的字符串),它在字符串中被重复。

我们举个例子来理解一下问题,

Input : str = "C program are easy to program"
Output : program

解决方法

解决该问题的简单方法是使用哈希映射数据结构。要找到第一个重复单词,我们将把每个单词及其计数(它在字符串中出现的次数)存储在哈希映射中。为此,我们将不断检查当前单词是否存在。

然后,我们将在哈希映射中打印第一个出现次数多于一次的单词。

示例

用程序说明我们解决方案的实际效果

#include <bits/stdc++.h>
using namespace std;
string findFirstRepeatWord(string str){
   istringstream iss(str);
   string word;
   unordered_map<string, int> wordCountMap;
   while (getline(iss, word, ' ')) {
      if (wordCountMap.find(word) != wordCountMap.end())
         wordCountMap[word] ++;
      else
         wordCountMap.insert(make_pair(word, 1));
   }
   istringstream iss2(str);
   while (getline(iss2, word, ' ')) {
      int count = wordCountMap[word];
      if (count > 1) {
         return word;
      }
   }
   return "NoRepetition";
}
int main(){
   string str = "C program are easy to program";
   string repeatedWord = findFirstRepeatWord(str);
   if (repeatedWord != "NoRepetition")
      cout<<"The first repeated word is '"<<repeatedWord<<"'";
   else
      cout<<"No word is Repeated in the string";
   return 0;
}

输出

The first repeated word is 'program'

此程序使用了很多内置函数,使得任务更加轻松。

更新于: 2022 年 1 月 27 日

1K+ 浏览量

开启你的 职业

完成课程,获得认证

开始
广告
© . All rights reserved.