fork download
  1. // CPP program to find the first
  2. // repeated character in a string
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Returns first repeating character in str.
  7. char firstRepeating(string &str)
  8. {
  9. // Creates an empty hashset
  10. unordered_set<char> h;
  11.  
  12. // Traverse the input array from left to right
  13. for (int i=0; i<str.length(); i++)
  14. {
  15. char c = str[i];
  16.  
  17. // If element is already in hash set, update x
  18. // and then break
  19. if (h.find(c) != h.end())
  20. return c;
  21.  
  22. else // Else add element to hash set
  23. h.insert(c);
  24. }
  25.  
  26. // If there was no repeated character
  27. return '\0';
  28. }
  29.  
  30. // Driver method to test above method
  31. int main ()
  32. {
  33. string str ;
  34. int t;
  35. cin>>t;
  36. while(t--){
  37. getline(cin,str);
  38. cout << firstRepeating(str);}
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.01s 5356KB
stdin
1
algorithms
stdout