If I got a string like "bookkeeper", how can I count the number of following characters that are repeating?
I would get an output like this: "1b2o2k2e1p1e1r"
Here's what I tried so far:
1 2 3 4 5 6 7 8 9 10 11 12 13
String s= "bookkeeper";
for (int i=0 ; i < s.length(); i++)
{
int sum = 0;
for (int j = 0; j < s.length(); j++)
{
if (s.at(i) == s.at(j))
sum++;
}
cout << sum<< s.at(i) ;
}
But the output gives me "1b2o2o2k2k3e3e1p3e1r" . Any help please?
If I understand correctly, this is an O(n) problem that you're both overthinking. The problem is to print subsequences of identical characters as the length of the sequence followed by the character.
So why do both your solutions use nested for loops? All you need is a variable to store the "current" character and how many of that character you've found in a sequence. Example solution (which I might redact later if I feel regret about posting it):
1 2 3 4 5 6 7 8 9 10 11
char current = input.front();
int count = 0;
for(char c: input) {
if(c == current) ++count;
else {
std::cout << count << current;
current = c;
count = 1;
}
}
std::cout << count << current << std::endl;