Do you have any idea how to count the number of distinct duplicated characters that appear in a string? For instance in the string "George" I have 2 characters, g and e. I tried with a while loop like
while (s.length()!=0){
if (s[i]==s[i+1]){
count++;
}
}
but this counts how many times a character appeas in the string. I can't find a method that can compare characters within the same string.
also, your [i+1] is safe on a string but would not work on other containers like a vector...
you can't say [last item] == [last item + 1] on most containers because [last item +1] is not valid memory. on a string, there is a hidden extra zero so its safe to tap.
there isnt a string only special snowflake algorithm built in for this, no.
it is less efficient that the set, but you can do something like:
std::transform (tolower or toupper)
followed by
std::sort()
followed by
std::adjacent_find()
which would make good uses of what c++ offers but is a very poor way to solve it. The problem is O(n) and the above is 2N+NlgN or so, much slower... and if you needed the original, it throws a copy in there too (though set is a partial copy, so that evens out).
the set trick is part of an extremely fast algorithm that you do not want to forget. It is useful for a variety of things, mostly sorting and counting and many things similar to counting.
int dc (string s) {
int i, j, c=0, k=0;
for (i=0; i<s.length(); ++i){
c=1;
for (j=i+1; j<s.length(); ++j){
if (s[i]==s[j]){
c++;
s[j] = '0';
}
}
if (c>1 && s[i]!='0'){
k++;
}
}
return k;
}