Reputation: 41
I have a problem that I really don't know how to solve. I need to count how many DISTINCT characters are in my string.
For example.
/
INPUT: wjmzbmr
OUTPUT: 6
/
Since the 'm' is showed twice, it should count it once.
My main thought is to sort the string before checking the characters and then count the DUPLICATES. When I finish counting how many duplicates are there, I just subtract the string length with my counter of duplicates.
Here's the code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
char temp;
cin >> input;
for(int i=0;i<input.length();i++)
{
for(int j=i;j<input.length();j++)
{
if(input[i] > input[j])
{
temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
}
//SORTED STRING PRINT HERE
cout<<input<<endl;
int counter=0;
for(int i=0;i<input.length()-1;i++)
{
if(input[i]==input[++i])
{
counter++;
}
}
int new_length = input.length() - counter;
cout<<"DUPLICATES: "<<counter<<endl;
cout<<"STRING LENGTH: "<<input.length()<<endl;
cout<<"WITHOUT DUPLICATES: "<<new_length<<endl;
return 0;
}
For some reasons this thing won't work on any string. Let's say I have a string like this.
/
INPUT: pppppp
OUTPUT: 3
/
P.S. I've provided multiple outputs just to check where is the issue. I couldn't find it so I am writing here. Thank you guys in advance.
Upvotes: 2
Views: 1291
Reputation: 31474
"I need to count how many DISTINCT characters are in my string"
If, as you mention, your string is sorted, then it's fairly trivial. Use std::unique in combination with erase
to remove all duplicates. After that, your string holds only unique characters, so its .size()
will be the count of unique characters.
Upvotes: 1