How to find the first repeated character in a string with C++

2 Answers

0 votes
#include <iostream>
#include <string>

char get_first_repeated_character(const std::string& s) {
    int len = s.length();

    for (int i = 0; i < len; ++i) {
        for (int j = 0; j < i; ++j) {
            if (s[i] == s[j]) {
                return s[i];
            }
        }
    }

    return ' ';
}

int main() {
    std::string s = "abcdxypcbop"; 
    char result = get_first_repeated_character(s);

    if (result != '-') {
        std::cout << "First repeated character: " << result << std::endl;
    } else {
        std::cout << "No repeated characters" << std::endl;
    }
}



/*
run:

First repeated character: c

*/

 



answered Sep 4, 2022 by avibootz
edited 6 days ago by avibootz
0 votes
#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
 
*/

 



answered 6 days ago by avibootz
...