Find the first non-repeating character in a string.
Sigiloso
#include #include #include // Function to find the first non-repeating character in a string. // It returns the character itself, or a null character if none is found. char findFirstNonRepeatingChar(const std::string& s) { // Create an unordered_map to store character frequencies. // The key is the character, and the value is its count. std::unordered_map charCounts; // First pass: Iterate through the string and populate the map with character counts. for (char c : s) { charCounts[c]++; } // Second pass: Iterate through the string again to find the first character // with a count of 1. for (char c : s) { if (charCounts[c] == 1) { return c; // Found the first non-repeating character. } } // If the loop completes, it means no non-repeating character was found. return '\0'; } int main() { std::string str1 = "geeksforgeeks"; char result1 = findFirstNonRepeatingChar(str1); if (result1 != '\0') { std::cout << "The first non-repeating character in \"" << str1 << "\" is: " << result1 << std::endl; } else { std::cout << "No non-repeating character found in \"" << str1 << "\"" << std::endl; } std::string str2 = "aabbcdeeff"; char result2 = findFirstNonRepeatingChar(str2); if (result2 != '\0') { std::cout << "The first non-repeating character in \"" << str2 << "\" is: " << result2 << std::endl; } else { std::cout << "No non-repeating character found in \"" << str2 << "\"" << std::endl; } std::string str3 = "aabbcc"; char result3 = findFirstNonRepeatingChar(str3); if (result3 != '\0') { std::cout << "The first non-repeating character in \"" << str3 << "\" is: " << result3 << std::endl; } else { std::cout << "No non-repeating character found in \"" << str3 << "\"" << std::endl; } return 0; }