Remove duplicate characters in a string
  • duplicate
  • character
  • string
  • remove
  •   
  • Posted: 2 years ago
  • Updated: 1 year ago
  • Edit
  • answers (2)
  • views (2264)

Suppose you are given a string. How will you remove the duplicate characters from it?


Posted Answers

 

# include
# include
# define NO_OF_CHARS 256
# define bool int


char *removeDups(char *str)
{
bool bin_hash[NO_OF_CHARS] = {0};
int ip_ind = 0, res_ind = 0;
char temp;


while (*(str + ip_ind))
{
temp = *(str + ip_ind);
if (bin_hash[temp] == 0)
{
bin_hash[temp] = 1;
*(str + res_ind) = *(str + ip_ind);
res_ind++;
}
ip_ind++;
}

/
*(str+res_ind) = '\0';

return str;
}


int main()
{
char str[] = "naiduu";
printf("%s", removeDups(str));
getchar();
return 0;
}

We can use the concept of hashtable to remove duplicates. The algorithm works as :


  • Convert the input string to a character array.
  • Iterate through the character array from beginning to end and check whether the element is in the
    hash table or not.
  • If found, skip the element. Otherwise, add the element in the hashtable.
  • Repeat the last two steps until all the elements in the character array has been iterated.
  • Return all the elements in the hash table.


Example - Let the input string be `AlgoQueue'.


Time complexity = O(n) .


public static void removeDuplicatesInAString(String input){

/* Convert the input string into a character array */
char[] myCharArray = string.toCharArray();

/* Create a new Set */
Set mySet = new LinkedHashSet ();
/* Iterate through the character array and add the elements in the set */
for (char c : myCharArray)
mySet.add(c);
/* Create a new string to display the result */
StringBuilder output = new StringBuilder();
for (Character char : mySet) {
output.append(char);
}
/* Display the result */
System.out.println(output.toString());
}

You need to Sign In to post your solution.