Topic description:
Given a string str, return the statistics string of str. For example, the statistical string of "aaabbadddffc" is " a_3_b_2_a_1_d_3_f_2_c_1 "
Idea: Traverse the string and use an integer variable to record the number, see the code for the specific process
C++ code:
#include<iostream>
#include<string>
using namespacestd;
int main(){
string str;
cin>>str;
if(str.empty())
return 0;
string res="";
res+=str[0];
//num stores the number of the same letter
int num= 1 ;
for(int i=1;i<str.size();i++){
//If the current character is different from the previous character, update res and set num to 1
if(str[i]!=str[i-1]){
res+="_"+to_string(num)+"_"+str[i];
num= 1 ;
}
//If the current character is the same as the previous character, add one directly to the count value, and then continue to traverse
else
num++;
}
//For the last character, you need to add num
res+="_"+to_string(num);
cout<<res<<endl;
return0;
}
Program running result:
aaabbadddffc
a_3_b_2_a_1_d_3_f_2_c_1
Program ended with exit code: 0