在 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+ 瀏覽量

開啟你的 職業

完成課程,獲得認證

開始
廣告