Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the number of unique characters in a string?

I have found nothing particular for this purpose.

I am trying to figure out a function that counts each of the characters' occurrences in a string, so that I can pull them out at the end from the length to find how many homogeneous characters are used in that string.

I've tried with nested loop, the first to apply and the second to scan the string and conditionally fulfill the character if it does not appear elsewhere in the string:

size_t CountUniqueCharacters(char *str)
{
    int i,j;
    char unique[CHAR_MAX];
    for(i=strlen(str); i>=0; i--)
    {
        for(j=strlen(str); j>=0; j--)
        {
            if(str[i] != unique[j])
                unique[j] = str[i];
        }
    }
    return strlen(unique);
}

This didn't work well.

This is useful if you are willing to limit someone to type lazy names such as "aaaaaaaaaaaaa".

like image 326
Edenia Avatar asked Jul 04 '14 11:07

Edenia


1 Answers

Here's a simple C++ solution. This method has O(n) complexity:

int countDistinct(string s) 
{ 

    unordered_map<char, int> m; 
  
    for (int i = 0; i < s.length(); i++) { 
        m[s[i]]++; 
    } 
  
    return m.size(); 
} 
like image 88
Nishil Shah Avatar answered Sep 30 '22 13:09

Nishil Shah