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

2 Answers

0 votes
#include <iostream>
    
int get_last_character_repeated(std::string s) { 
    int len = s.length(), ch_idx = -1;
      
    for (int i = 0; i < len; i++) { 
        for (int j = i + 1; j < len; j++) { 
            if (s[i] == s[j]) { 
                ch_idx = i;
                break;
            } 
        }
    } 
    return ch_idx; 
}   
 
int main() {
    std::string s = "abcdxypcbadom"; 
    int i = get_last_character_repeated(s); 
      
    if (i == -1) 
        std::cout << "Not found"; 
    else
        std::cout << s[i]; 
}
 
 
/*
run:
 
d
 
*/

 



answered Jan 24, 2020 by avibootz
edited Nov 1 by avibootz
0 votes
#include <iostream>
#include <array>
#include <string>

/**
 * Finds the last repeated character in a string.
 *
 * Examples:
 *   "abca"         -> 'a'
 *   "abcbd"        -> 'b'
 *   "abcde"        -> '\0' (no repeated character)
 *   "abcdxypcbop"  -> 'p'
 *   "abcdxypcbadom"-> 'd'
 *
 * Time Complexity: O(n)
 * Space Complexity: O(1)
 *
 * @param str Input string.
 * @return The last repeated character, or '\0' if none exists.
 */
char findLastRepeatedCharacter(const std::string& str)
{
    // Frequency table for all possible unsigned char values.
    std::array<int, 256> frequency{};

    // Count character occurrences.
    for (unsigned char ch : str) {
        ++frequency[ch];
    }

    // Traverse from right to left.
    for (auto it = str.rbegin(); it != str.rend(); ++it) {
        unsigned char ch = static_cast<unsigned char>(*it);

        if (frequency[ch] > 1) {
            return *it;
        }
    }

    // No repeated character found.
    return '\0';
}

int main()
{
    std::cout << findLastRepeatedCharacter("abca") << '\n';          
    std::cout << findLastRepeatedCharacter("abcbd") << '\n';         

    char result = findLastRepeatedCharacter("abcde");
    std::cout << (result ? result : ' ') << '\n';                   

    std::cout << findLastRepeatedCharacter("abcdxypcbop") << '\n';  
    std::cout << findLastRepeatedCharacter("abcdxypcbadom") << '\n'; 
}

 
 
/*
run:
 
a
b
 
p
d
 
*/

 



answered Nov 1 by avibootz
...