Strings: Find the first repeated word in a string

Problem Statement:

You are given a string, you need find the 1st repeated word in a string.

Example

Input: : "I am what I am"
Output: I

Here “I” is the first repeated word in the string.

Solution

The solution is very simple.

Here we take a hashmap that has a word and its count.

Then we traverse the string and for each word of that string we increase the count if the string is already present else we create a new entry.

Then we traverse the hashmap and get the word whose count is more than 1.

Solution in C++

#include <vector>    
#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <string>
#include <unordered_map>
#include <queue>
#include <sstream> 

using namespace std;

string findFirstRepeated(string s)
{

   istringstream iss(s);
   string token;

   unordered_map<string, int> word_with_count;

   while (getline(iss, token, ' ')) 
   {
      if (word_with_count.find(token) != word_with_count.end())
      {  
        //old word, increase count     
         word_with_count[token] += 1; 
      }
      else
      {
         // as it is a new word, insert it
         word_with_count.insert(make_pair(token, 1));  
      }  
   }


   istringstream iss2(s);
   while (getline(iss2, token, ' ')) 
   {
      //now check if the word exist and the count is greater than 1
      int count = word_with_count[token];
      if (count > 1) 
      {
         return token;
      }
   }

   return "False";
}

// driver program
int main()
{
   string s("I am what I am");
   string firstWord = findFirstRepeated(s);
   if (firstWord != "False")
      cout << "The first repeated word is = " << firstWord << endl;
   else
      cout << "No Repetitionn";
   return 0;
}

Output:

The first repeated word is = I

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *