Skip to content

Instantly share code, notes, and snippets.

@iamazeem
Created April 10, 2018 11:25
Show Gist options
  • Select an option

  • Save iamazeem/e4dc4aa9147d4c23fb0807e79f466ef8 to your computer and use it in GitHub Desktop.

Select an option

Save iamazeem/e4dc4aa9147d4c23fb0807e79f466ef8 to your computer and use it in GitHub Desktop.
How to find first recurring character in a string
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <vector>
#include <array>
#include <utility>
#include <algorithm>
#include <unordered_map>
using Result = std::pair< char, bool >;
const Result findFirstRecurringCharacter( const std::string& s ) noexcept;
int main( void )
{
const std::vector< std::string > strings
{
"ABCDA",
"ABCDE",
"ABCBA"
};
for ( auto& s : strings )
{
auto result = findFirstRecurringCharacter( s );
std::cout << std::quoted( s ) << '\n'
<< "Found? "
<< std::boolalpha << result.second << '\n'
<< ( result.second ? result.first : '\0' )
<< "\n\n";
}
return EXIT_SUCCESS;
}
const Result findFirstRecurringCharacter( const std::string& s ) noexcept
{
using LookupTable = std::unordered_map< char, char >;
LookupTable table;
for ( auto& c : s )
{
if ( table.find( c ) != table.end() )
{
return { c, true };
}
table[ c ] = c;
}
return { '\0', false };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment