saifalvi's blog

By saifalvi, history, 6 years ago, In English

236A - Boy or Girl In this problem we have to find out if the number of distinct characters in one's user name is odd or even. How to count the unique characters in a string in c++? TIA.

  • Vote: I like it
  • -5
  • Vote: I do not like it

| Write comment?
»
6 years ago, hide # |
 
Vote: I like it -20 Vote: I do not like it
string s;
cin >> s;
sort(s.begin(), s.end());
s.erase(unique(s.begin(), s.end()), s.end());
if (s.size() % 2 == 0) {
    cout << "CHAT WITH HER!\n";
} else {
    cout << "IGNORE HIM!\n";
}
»
6 years ago, hide # |
 
Vote: I like it -12 Vote: I do not like it

Sort the vector (call this vector v)

Then use v.erase(unique(v.begin(), v.end()), v.end());

Then your answer is just the size of the vector afterwards.

Read about erase and unique to understand what they do.

Alternatively you could insert all the elements in a set and return it's size

»
6 years ago, hide # |
 
Vote: I like it +9 Vote: I do not like it

If you are interested only in the count of unique characters of a string x, it suffices to do the following:

sort(x.begin(), x.end());
int unique_chars_cnt = unique(x.begin(), x.end()) - x.begin();
»
3 years ago, hide # |
Rev. 2  
Vote: I like it +1 Vote: I do not like it

Anyway I think using a bucket is better than sorting and unique() since we only have lowercase Latin letters.

string s;
cin >> s;
bool bucket[26];
memset(bucket, 0, sizeof(bucket));
int count = 0;
for (char c : s) {
    if (!bucket[c-'a']) {
        bucket[c-'a'] = true;
        count++;
    }
}
cout << (count%2?"IGNORE HIM!":"CHAT WITH HER!") << endl;
»
3 years ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

One-liner if you're really lazy: set(s.begin(), s.end()).size()