Monday, 9 November 2015

Print all the duplicates in the input string

Write an efficient C program to print all the duplicates and their counts in the input string
Algorithm: Let input string be “geeksforgeeks”
1: Construct character count array from the input string.
count[‘e’] = 4
count[‘g’] = 2
count[‘k’] = 2
……
2: Print all the indexes from the constructed array which have value greater than 0.
Solution
# include <stdio.h>
# include <stdlib.h>
# define NO_OF_CHARS 256
 
/* Fills count array with frequency of characters */
void fillCharCounts(char *str, int *count)
{
   int i;
   for (i = 0; *(str+i);  i++)
      count[*(str+i)]++;
}
 
/* Print duplicates present in the passed string */
void printDups(char *str)
{
  // Create an array of size 256 and fill count of every character in it
  int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));
  fillCharCounts(str, count);
 
  // Print characters having count more than 0
  int i;
  for (i = 0; i < NO_OF_CHARS; i++)
    if(count[i] > 1)
        printf("%c,  count = %d \n", i,  count[i]);
 
  free(count);
}
 
/* Driver program to test to pront printDups*/
int main()
{
    char str[] = "test string";
    printDups(str);
    getchar();
    return 0;
}

Output:
s,  count = 2
t,  count = 3

Time Complexity: 
O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

No comments:

Post a Comment