First Repeated Character in a String in C++

In this CPP tutorial, we are going to discuss about the first repeating character in a string using set.

Here, we go through some prerequisites of set that we need in the code :-

What is Set ?

Sets are a type of containers in which each element are unique and no duplicates are allowed in a set. In set, value of element identifies it.

Once the value is inserted in a set it can not be modified.

Syntax:-                             set<data_type>set_name;

How to add element in set ?

To add element in a set we use set.insert(value) function.

Syntax :-                     set_name.insert( value );

where set_name is the name of set we have declared during declaration of set.

value is the element to be added in set.

How to find an element in set ?

To find an element in set we use set_name.find( element ) function.

Syntax :-         set_name.find ( element );

How to check if an element exist in set or not ?

To check whether an element exist in set or not we  check if set_name.find( element ) == set_name.end() if this is true then this element not exist in set previously otherwise exist where set_name.end() is the position just after the last element of set.

Syntax :-                    set_name.find( element ) == set_name.end();

Algorithm

  • Input the string s.
  • Declare a set of characters “sett”.
  • Read the string and check if the given character exist in the string before by using function set_name.find( element ) == set_name.end() otherwise insert the element in the set.
  • When you get the first repeating character then break from there if we does not find and repeating character then print “-1”

CPP code implementation of finding first repeating character in a string

#include<bits/stdc++.h>
using namespace std;

int i;

 int main()
 {
     int t;
      cin>>t;
      
      while(t--)
      {
        string s;
         cin>>s;
   
      
      set<char>sett;
      
      int f=0;
      
       for(i=0;i<s.length();i++)
       {
           if(sett.find(s[i])!=sett.end())
            {
                cout<<s[i]<<endl;
                
                 f=1;
                
                  break;
            }
            
            else
               sett.insert(s[i]);
       }
       
       if(f==0)
        cout<<"-1"<<endl;
 }}

INPUT

3
Codespeedy
Coding
Ghostrider

OUTPUT

e
-1
r

Thanks For Reading !!

Please, ask your doubts and for any suggestion comment in the comment section below.

Leave a Reply