Method-3: Using Hashing
In this case we will use a separate array (which will act as hash table) to store the number of occurrences of a character in the string.
Step-1: Populate the hash (array) to store the number of times a character appears in the array.
If original string is "social.ritambhara.in", then the hash array will have
arr['s'] = 1
arr['o'] = 1
arr['c'] = 1
arr['i'] = 3
arr['a'] = 4
arr['l'] = 1
arr['.'] = 2
arr['r'] = 2
arr['t'] = 1
arr['m'] = 1
arr['b'] = 1
arr['h'] = 1
Step-2: Now traverse the array from backward direction and for each character
- remove the character if its hash count is > 1.
- Decrease the corresponding hash count.
Code:
void removeDuplicatesUsingHash(char* str)
{
int hash[256] = {0};
// Populating the hash.
for(int i=0; str[i] != '\0'; i++)
hash[str[i]]++;
// traversing the array from back and
// removing the characters if its hash value is > 1
for(int i = strlen(str)-1; i>0; i--)
{
// Need to do this here, because str[i] may change in loop below.
hash[str[i]]--;
if(hash[str[i]] > 0)
{
// Removing the character.
int j=i;
for(; str[j] != '\0'; j++)
str[j] = str[j+1];
}
}
}
Next: Java Code..
where is n in array?
n is the size of string.