#include <iostream>
#include <string>
#include <unordered_set>
/**
* Finds the first repeated character in a string.
*
* Examples:
* "abca" -> 'a'
* "abcbd" -> 'b'
* "abcde" -> '\0' (no repeated character)
* "abcdxypcbop" -> 'c'
*
* Time Complexity: O(n)
* Space Complexity: O(n)
*
* @param str Input string.
* @return First repeated character, or '\0' if none exists.
*/
char findFirstRepeatedCharacter(const std::string& str)
{
std::unordered_set<char> seen;
for (char ch : str) {
// insert() returns a pair:
// - iterator to the element
// - bool indicating whether insertion occurred
if (!seen.insert(ch).second) {
return ch;
}
}
// No repeated character found
return '\0';
}
int main()
{
std::cout << findFirstRepeatedCharacter("abca") << '\n';
std::cout << findFirstRepeatedCharacter("abcbd") << '\n';
char result = findFirstRepeatedCharacter("abcde");
if (result != '\0')
std::cout << result << '\n';
else
std::cout << "No repeated character\n";
std::cout << findFirstRepeatedCharacter("abcdxypcbop") << '\n';
}
/*
run:
a
b
No repeated character
c
*/