Created
April 10, 2018 11:25
-
-
Save iamazeem/e4dc4aa9147d4c23fb0807e79f466ef8 to your computer and use it in GitHub Desktop.
How to find first recurring character in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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