Find the first repeated character in a string using C++.

C++Server Side ProgrammingProgramming

Suppose we have a string; we have to find the first character that is repeated. So is the string is “Hello Friends”, the first repeated character will be l. As there are two l’s one after another.

To solve this, we will use the hashing technique. Create one hash table, scan each character one by one, if the character is not present, then insert into a hash table, if it is already present, then return that character.

Example

 Live Demo

#include<iostream>
#include<unordered_set>
using namespace std;
char getFirstRepeatingChar(string &s) {
   unordered_set<char> hash;
   for (int i=0; i<s.length(); i++) {
      char c = s[i];
      if (hash.find(c) != hash.end())
         return c;
      else
         hash.insert(c);
   }
   return '\0';
}
int main () {
   string str = "Hello Friends";
   cout << "First repeating character is: " << getFirstRepeatingChar(str);
}

Output

First repeating character is: l
raja
Published on 30-Oct-2019 11:02:11
Advertisements