saifalvi's blog

By saifalvi, history, 5 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?
»
5 years ago, # |
  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";
}
»
5 years ago, # |
  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

»
5 years ago, # |
  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();
  • »
    »
    19 months ago, # ^ |
      Vote: I like it -26 Vote: I do not like it

    can you describe it please?

    • »
      »
      »
      19 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Check this out. (sorting is necessary to get all similar characters in a continuous segment)

      • »
        »
        »
        »
        19 months ago, # ^ |
          Vote: I like it -20 Vote: I do not like it

        I have understood the sorting. But i can't understood this: unique(x.begin(), x.end()) — x.begin();

        • »
          »
          »
          »
          »
          19 months ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          Unique return iterator to last character. Unique — begin would give the index of last character which is also the number of unique characters in the string.

»
19 months ago, # |
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;
»
19 months ago, # |
  Vote: I like it +3 Vote: I do not like it

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