Your select of r
(for next starting position) is not right. I suggest using a r_next
to mark the next character which is the nearest different character from the current searching one. The a flag pick_next
to indicate if r_next
is set or not (0 not set, 1 set). The next searching will set to start from r_next
:
#include <iostream>
using namespace std;
int main()
{
string str = "aafffkhjskk";
int pick_next, r_next, count;
cout << str << endl;
int r = 0, count = 0;
while ((r + count) < str.size()) {
count = 0; // Str 0 strating point
pick_next = 0;
for (int in = r; in < str.length(); in++) {
// r = in because increment finding element
if (str[r] == str[in]) {
count++;
}
// mark the first non-identical position
else {
if (pick_next == 0) {
r_next = in;
pick_next = 1;
}
}
}
cout << "count = " << count << " ****** " << str[r] << endl;
r = r_next; // place r for next search
} // end of while
}
Test run:
$ ./a.exe
aafffkhjskk
count = 2 ****** a
count = 3 ****** f
count = 3 ****** k
count = 1 ****** h
count = 1 ****** j
count = 1 ****** s
count = 2 ****** k
--
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…