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

2 Answers

0 votes
#include <stdio.h> 
#include <string.h> 
   
int get_last_character_repeated(char* s) { 
    int ch_idx = -1;
     
    for (int i = 0; i < s[i]; i++) { 
        for (int j = i + 1; j < s[i]; j++) { 
            if (s[i] == s[j]) { 
                ch_idx = i;
                break;
            } 
        }
    } 
    return ch_idx; 
}  
int main() {
    char s[] = "abcdxypcbadom"; 
    int i = get_last_character_repeated(s); 
     
    if (i == -1) 
        printf("Not found\n"); 
    else
        printf("%c\n", s[i]); 
         
    return 0;
}
 
 
 
/*
 
d
 
*/

 



answered Jan 24, 2020 by avibootz
edited Jan 24, 2020 by avibootz
0 votes
#include <stdio.h>

/*
 * Finds the last repeated character in a string.
 *
 * Examples:
 * "abca"         -> 'a'
 * "abcbd"        -> 'b'
 * "abcde"        -> '\0' (no repeated character)
 * "abcdxypcbop"  -> 'p'
 *
 * Time Complexity: O(n)
 * Space Complexity: O(1)
 *
 * Returns:
 *   The last repeated character, or '\0' if no character repeats.
 */
char findLastRepeatedCharacter(const char *str)
{
    if (str == NULL) {
        return '\0';
    }

    int frequency[256] = {0};

    /* First pass: count occurrences of each character. */
    const char *p = str;
    while (*p) {
        frequency[(unsigned char)*p]++;
        p++;
    }

    /* Second pass: scan from right to left. */
    p--;  /* Move back from '\0' to the last character. */

    while (p >= str) {
        if (frequency[(unsigned char)*p] > 1) {
            return *p;
        }
        p--;
    }

    return '\0';
}

int main(void)
{
    printf("%c\n", findLastRepeatedCharacter("abca"));         
    printf("%c\n", findLastRepeatedCharacter("abcbd"));        

    char result = findLastRepeatedCharacter("abcde");
    printf("%c\n", result ? result : ' ');                     

    printf("%c\n", findLastRepeatedCharacter("abcdxypcbop"));  
    printf("%c\n", findLastRepeatedCharacter("abcdxypcbadom")); 

    return 0;
}



/*
run:

a
b
 
p
d

*/

 



answered Nov 1 by avibootz
...