Блог пользователя saifalvi

Автор saifalvi, история, 4 года назад, По-английски

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.

  • Проголосовать: нравится
  • -5
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится -20 Проголосовать: не нравится
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";
}
»
4 года назад, # |
  Проголосовать: нравится -12 Проголосовать: не нравится

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

»
4 года назад, # |
  Проголосовать: нравится +9 Проголосовать: не нравится

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();
»
16 месяцев назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

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;
»
16 месяцев назад, # |
  Проголосовать: нравится +3 Проголосовать: не нравится

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