
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
First Non-Repeating Character Using One Traversal of String in C++
In this tutorial, we are going to learn how to find the first non-repeating character in the given string. Let's see an example.
Input −tutorialspoint
Output −u
Let's see the steps to solve the problem.
Initialize the string.
Initialize a map char and array to store the frequency of the characters in the string.
Iterate over the string.
Find the frequency of each character and store them in the map.
Store the index of the character as well.
Iterate over the character frequencies in the map.
Print the first character with the frequency 1.
Example
Let's see the code.
#include <bits/stdc++.h> #include <map> using namespace std; void findDistinctCharacters(string random_string) { // initializing char count map<char, int[2]> chars; // iterating over the string for (int i = 0; i < random_string.size(); ++i){ chars[random_string[i]][0]++; chars[random_string[i]][1] = i; } int char_index = INT_MAX; // printing the first char with frequency 1 for (auto item: chars) { // checking the frequency if (item.second[0] == 1) { char_index = min(char_index, item.second[1]); } } // printing the first char with frequency 1 cout << random_string[char_index] << u; } int main() { findDistinctCharacters("tutorialspoint"); return 0; }
Output
If you run the above code, then you will get the following result.
u
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements