94. Remove Duplicate Characters from a String

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>

void remove_duplicates(char *str) {
    //Create a hash table (1-byte(char) flags array of all posisble ASCII characters)
    uint8_t hash[256] = {0};
    uint8_t read_index = 0;
    uint8_t write_index = 0;
    //Loop through every character of string
    while(str[read_index] != '\0'){
        uint8_t cur_char = (uint8_t)str[read_index]; //Cast char to uint8_t number val
        if(hash[cur_char]==0){ //If char not flagged in the hash table (not duplicate)
            str[write_index] = str[read_index]; //Copy the char into string 
            write_index++; //increment write_index
            hash[cur_char] = 1; //Set char seen flag in hash table
        }
        //printf("Loop: %d, %s\n",read_index,str);
        read_index++;
    }
    //Cut the remaining end of string
    str[write_index] = '\0';
    
    //Check if the current character has been seen before (by checking for a 1 in hash table)
    //If not, set ASCII flag to 1 & add char to current string

    }

int main() {
    char str[101];
    fgets(str, sizeof(str), stdin);

    // Remove newline
    uint8_t i = 0;
    while (str[i]) {
        if (str[i] == '\n') {
            str[i] = '\0';
            break;
        }
        i++;
    }

    remove_duplicates(str);
    printf("%s", str);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote