fork download
  1. #include <iostream>
  2. #include <queue>
  3.  
  4. using namespace std;
  5.  
  6. void first_non_repeating_character(const string& stream) {
  7.  
  8. // Initializing an array to store the frequency of characters (ASCII range)
  9. int frequency[128] = {0};
  10. // Initializing a queue to store characters
  11. queue<char> queue;
  12.  
  13. for (char c : stream) {
  14. int index = static_cast<int>(c); // Converting character to its ASCII value
  15. frequency[index]++; // Incrementing the frequency of the character
  16.  
  17. if (frequency[index] == 1) { // If the frequency becomes 1, it's the first occurrence
  18. queue.push(c); // and hence we enqueue the character into the queue
  19. }
  20. }
  21.  
  22. // Removing characters from the front of the queue until we find a non-repeating character
  23. // (i.e., a character with frequency 1) or until the queue is empty
  24. while (!queue.empty() && frequency[static_cast<int>(queue.front())] > 1) {
  25. queue.pop(); // Removing characters with frequency greater than 1
  26. }
  27.  
  28. // If the queue is not empty, the front element is the first non-repeating character
  29. // Otherwise, there's no non-repeating character found so far.
  30. if (!queue.empty()) {
  31. cout <<"The first non repeating character in the string '"<<stream<<"' is: "<< queue.front() <<endl; // the first non-repeating character
  32. } else {
  33. cout <<"There is no non-repeating character in the string: '"<<stream<<"'"<<endl; // if no non-repeating character found
  34. }
  35. }
  36.  
  37. int main() {
  38. string stream = "abacabad";
  39. first_non_repeating_character(stream);
  40. cout << endl;
  41.  
  42. return 0;
  43. }
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
The first non repeating character in the string 'abacabad' is: c